简体   繁体   中英

How to Determine a Common Element in a Set of Tuples - Python

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

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}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM