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

2020-02-11 02:10发布

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.

3条回答
手持菜刀,她持情操
2楼-- · 2020-02-11 02:39

I think you want this: ( Use all )

>>> all(i in (1,2,3,4,5) for i in (1,2))
True 
查看更多
【Aperson】
3楼-- · 2020-02-11 02:45

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
查看更多
一夜七次
4楼-- · 2020-02-11 02:52

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
查看更多
登录 后发表回答