如何在一组元组中查找单个值?

时间:2012-02-14 09:02:14

标签: python set tuples

假设我有这个集合:

a = set([(1,2),(3,4),(5,6)])

如何在该套装中找到“3”或“7”?

4 个答案:

答案 0 :(得分:4)

使用any()

any(3 in t or 7 in t for t in a)

答案 1 :(得分:2)

a = set([(1,2),(3,4),(5,6)])
b = set((3,7))
any(b&set(p) for p in a)
# True

@RikPoggi也建议使用isdisjoint,即使没有创建集也可以使用:

any(not b.isdisjoint(p) for p in a)

答案 2 :(得分:1)

for tuple in a:
    for value in tuple:
        if value in [3, 7]:
            print 'found'

答案 3 :(得分:0)

>>> from itertools import chain
>>> if set(chain(*set([(1,2),(3,4),(5,6)])))&set([3,7]):
...     print True
...     
True