Question

I am trying to find whether any number from one list exists in another list. I am doing it in following way:

print any([20.0,0.0,19.0,1.0]) in [20.0,0.0]

This prints

False

Whereas it should be

True

Can anyone explain why is this happening?

Était-ce utile?

La solution

Because that's not what any does. any takes an iterable of values, interprets them as booleans, and returns a boolean indicating whether any of them were True. At least one of [20.0, 0.0, 19.0, 1.0] is nonzero, which means it counts as True, so any([20.0, 0.0, 19.0, 1.0]) evaluates to True, and your print statement is equivalent to print True in [20.0, 0.0]. Which is itself False.

To do this with any, use a generator expression:

print any(x in [20.0, 0.0] for x in [20.0, 0.0, 19.0, 1.0])

If you're doing this for any significant number of values, you'll get major performance improvements from using a set. in on a list is linear with the length of the list, while in on a set is constant time.

targets_set = set([20.0, 0.0])
print any(x in targets_set for x in [20.0, 0.0, 19.0, 1.0])

Autres conseils

any returns True if any item in the iterable is true. (non-zero number is true).

>>> any([20.0,0.0,19.0,1.0])
True

any([20.0,0.0,19.0,1.0]) in [20.0,0.0] is like True in [20.0, 0.0].

To get what you want, try following (using generator expression).

>>> any(n in [20.0, 0.0] for n in [20.0, 0.0, 19.0, 1.0])
True

You could also create difference between two sets and check if there is any element in result set

intersection = set([20.0,0.0,19.0,1.0]) & set([20.0,0.0])
print (len(intersection) > 0)

set([20.0,0.0,19.0,1.0]) & set([20.0,0.0]) creates new set set([0.0, 20.0]) which contains elements which are in both left and right set and len(intersection) > 0 returns True if there is at least one element in iterable (in this case set)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top