代码之家  ›  专栏  ›  技术社区  ›  user9689131

如何确定一组元组中的公共元素-Python

  •  2
  • user9689131  · 技术社区  · 6 年前

    假设我有一组元组,每个元组包含两个整数。

    mySet = ((1, 3), (3, 4), (3, 5))
    

    找到 公共元素 来自元组?

    对于这种情况 输出 将是:

    3
    
    2 回复  |  直到 6 年前
        1
  •  6
  •   BcK    6 年前

    这里有一个快速的解决方案。

    编辑为包含genexpr,而不是列表理解

    mySet = {(1, 3), (3, 4), (3, 5)}
    mySet = (set(tup) for tup in mySet)
    
    print(set.intersection(*mySet))
    
    # {3}
    
        2
  •  3
  •   Sohaib Farooqi    6 年前

    可以通过使用转换嵌套元组来设置和计算每个元组的交集来实现这一点。

    from functools import reduce
    
    def common_elements(s):
        return reduce(set.intersection, map(set, s))
    
    >>> common_elements({(1, 3), (3, 4), (3, 5)})
    >>> {3}
    >>> common_elements({(1, 1), (1, 4), (3, 5)})
    >>> set()
    

    Timeit基准

    $ python -m timeit -s "from functools import reduce" -s "s = {(1, 3), (3, 4), (3, 5)}" "reduce(set.intersection, map(set, s))"
    $ 1000000 loops, best of 3: 1.09 usec per loop
    
    $ python -m timeit -s "from functools import reduce" -s "s = {(0,1) for _ in range(100)}" "reduce(set.intersection, map(set, s))"
    $ 1000000 loops, best of 3: 0.5 usec per loop