5
$\begingroup$

I have a list of the form

{
{{1, 2}, 0.395}, 
{{1, 3}, ∞}, 
{{1, 4}, ∞}, 
{{2, 3}, 1}, 
{{2, 4}, ∞},
{{3, 4}, ∞}
}

and I hope to find the elements whose list contains 2 or 3. Namely the return should be

{{1},{2},{4},{5},{6}}

I tried

Position[binaryCollisionTime, _?(ContainsAny[#[[1]], {2, 3}] &)]

but it gives errors but I am not sure why.

$\endgroup$
3
$\begingroup$
Position[ContainsAny[#, {2,3}]&@@@lst, True]

Alternatively:

Position[ContainsAny[#[[1]], {2,3}]&/@lst, True]

{{1}, {2}, {4}, {5}, {6}}

| improve this answer | |
$\endgroup$
  • $\begingroup$ Thanks! This is the most reader-friendly code so far! $\endgroup$ – water liu Feb 16 at 14:03
7
$\begingroup$

Thank you for the example input and output data. That is very helpful.

Try

list={{{1, 2}, 0.395}, {{1, 3}, ∞}, {{1, 4}, ∞},
   {{2, 3}, 1}, {{2, 4}, ∞},{{3, 4}, ∞}};
Position[list,{{___,2|3,___},_}]

which instantly returns the desired

{{1}, {2}, {4}, {5}, {6}}

The preceeding and trailing triple underscores match zero or more things. That is followed by the pattern which matches either a 2 or a 3. That way this will match a 2 or 3 that is the first or the second element inside your inner list. The extra layer of braces and final underscore match the rest of each item in your list.

As you see, I do get a {5} in my result that you do not show in your desired output. I am not certain if I might have made a mistake that results in this or not, but I can't see how I would not get a {5}. If you can explain my misunderstanding then I will try to correct this.

| improve this answer | |
$\endgroup$
  • $\begingroup$ Thanks! I should indeed get a {5}, I have edited the question. $\endgroup$ – water liu Feb 16 at 14:04
5
$\begingroup$
lst = {{{1, 2}, 0.395}, {{1, 3}, ∞}, {{1, 4}, ∞}, {{2, 3},  1}, {{2, 4}, ∞}, {{3,  4}, ∞}}; 

Position[lst, _?(Not @* FreeQ[2 | 3]), 1]

{{1}, {2}, {4}, {5}, {6}}

| improve this answer | |
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.