I have made the following hypotheses:
The list could have repeated tuples. In the groups of the result instead we do not want repetitions.
The tuple (x,y)
is different from the tuple (y,x)
.
The order in which the groups are listed in the final result, or the tuples within each group, is irrelevant.
With these conditions, the following code creates a dictionary whose keys are numbers that have been observed in some tuple (for example, 1, 2, 3, etc.) and whose values are sets with the tuples that contain that number.
I think the simplest way to understand it is by example.
from collections import defaultdict
lista = [(1,2),(2,5),(3,4),(4,1),(8,2)]
grupos = defaultdict(set)
for tupla in lista:
for v in tupla:
grupos[v].add(tupla)
Result (variable grupos
):
defaultdict(set,
{1: {(1, 2), (4, 1)},
2: {(1, 2), (2, 5), (8, 2)},
3: {(3, 4)},
4: {(3, 4), (4, 1)},
5: {(2, 5)},
8: {(8, 2)}})
Which reads as follows:
- Tuples in which appears 1, = >
(1, 2), (4, 1)
- Tuples in which appears 2, = >
(1, 2), (2, 5), (8, 2)
- Tuples in which 3 appears, = >
(3, 4)
- etc.
Now we can only stay with the cases in which the set has more than one element, and thus form the list with the result you were looking for by means of the following list comprehension :
[ list(tuplas) for n, tuplas in grupos.items() if len(tuplas)> 1]
[[(1, 2), (4, 1)], [(1, 2), (2, 5), (8, 2)], [(4, 1), (3, 4)]]