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