How to Determine a Common Element in a Set of Tupl

2019-07-19 16:41发布

问题:

Say I have a set of tuples, with each tuple containing two integers.

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

What would be the best way to find a common element from tuples?

For this case output will be :

3

回答1:

Here is a quick solution.

Edited to include genexpr instead of list comprehension

mySet = {(1, 3), (3, 4), (3, 5)}
mySet = (set(tup) for tup in mySet)

print(set.intersection(*mySet))

# {3}


回答2:

You can achieve this by using converting nested tuples to set and calculating intersection of each.

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 benchmark

$ 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