【问题标题】:How to look for a single value in a set of tuples?如何在一组元组中查找单个值?
【发布时间】:2012-02-14 09:02:14
【问题描述】:

假设我有这一套:

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

如何测试是否可以在该集合中找到“3”或“7”?

【问题讨论】:

    标签: python set tuples


    【解决方案1】:

    any():

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

    【讨论】:

    • 或许这更清楚:any(3 in tup for tup in setOfTuples)
    • +1 非常清楚。 @ninjagecko 只会给出一个 NameError ;-)
    • @ChrisWesseling:是的,显然 =) 我假设读者会意识到 setOfTuples 显然是 a
    【解决方案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)
    

    【讨论】:

    • 从python-2.7你可以使用b = {3,7},最后一行也可以是:any(not b.isdisjoint(set(p)) for p in a)
    • -1:你写了一个重言式:>>> a = set([(1,2),(3,4),(5,6)]) >>> b = set((8,7)) >>> any(b|set(p) for p in a) True ; 8 或 7 都不是,但我得到了 True。 @RikPoggi 的正确的。
    • @ChrisWesseling - 你是对的,错误的运算符(or 而不是 and),谢谢,已修复!
    【解决方案3】:
    for tuple in a:
        for value in tuple:
            if value in [3, 7]:
                print 'found'
    

    【讨论】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多