Question

Given

a = [1, 2, 3, 4]
b = [10, 1, 20, 30, 4]

I would like to check if any of the elements in a is present in b.

>>> [i in b for i in a]
Out[45]: [True, False, False, True]

The code above does part of the job. The next step could be a reduce. However, I did not get the code below working without my own implementation of the or function.

def is_any_there(a, b):
    one_by_one = [i in b for i in a]

    def my_or(a,b):
        if a or b:
            return True
        else:
            return False
    return reduce(my_or, one_by_one)

How can I avoid the rewriting of the or function?

Était-ce utile?

La solution

is_there_any just reimplements the any function, available since Python 2.5:

any(x in b for x in a)

Further, my_or is already available as operator.or_ in the standard library.

Autres conseils

If items are hashable then you can use set.isdisjoint():

>>> a = [1, 2, 3, 4]
>>> b = [10, 1, 20, 30, 4]
>>> not set(a).isdisjoint(b)
True
>>> b = [10, 10, 20, 30, 40]
>>> not set(a).isdisjoint(b)
False
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top