How to check if all elements in a tuple or list ar

2020-02-11 02:46发布

问题:

For example, I want to check every elements in tuple (1, 2) are in tuple (1, 2, 3, 4, 5). I don't think use loop is a good way to do it, I think it could be done in one line.

回答1:

You can use set.issubset or set.issuperset to check if every element in one tuple or list is in other.

>>> tuple1 = (1, 2)
>>> tuple2 = (1, 2, 3, 4, 5)
>>> set(tuple1).issubset(tuple2)
True
>>> set(tuple2).issuperset(tuple1)
True


回答2:

I think you want this: ( Use all )

>>> all(i in (1,2,3,4,5) for i in (1,2))
True 


回答3:

Another alternative would be to create a simple function when the set doesn't come to mind.

def tuple_containment(a,b):
    ans = True
    for i in iter(b):
        ans &= i in a
    return ans

Now simply test them

>>> tuple_containment ((1,2,3,4,5), (1,2))
True
>>> tuple_containment ((1,2,3,4,5), (2,6))
False