# group tuples of a list [closed]

2

I am interested in grouping tuples of two elements of a list of tuples that share an element. How could I do this in python?

For example, if I have the list `[(1,2),(2,5),(3,4),(4,1),(8,2)]` the answer should be `[[(1,2),(2,5),(8,2)],[(3,4),(4,1)],[(1,2),(4,1)]]`

One of the requirements is that the solution be efficient because the original list of tuples is quite large.

asked by ekth0r 28.11.2018 в 16:26
source

0

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:
``````

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)}})
``````

• 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)]]
``````

source
1

``````list = [(1, 2), (2, 5), (3, 4), (4, 1), (8, 2)]
L = []
B = []

for i in range(len(list)):
#print(list[i])
if 2 in list[i]:
L.append(list[i])
print(">>>"+str(L))
else:
B.append(list[i])
print(">>>"+str(B))

print(str(L)+","+str(B))
``````

Result:

``````[[(1,2),(2,5),(8,2)],[(3,4),(4,1)]]
``````

PS: I have put the static number 2 (to do the checks) since I see that you comment that you want to put together a list of tuples that share some element, however the (4,1) also shares element with (1,2) ).

Greetings!