Given that:
list=[[1,2,3],[3,4,5],[5,6],[6,7],[9,10],[10,11]]
I have asked a similar question before, I have tried the code on
how to merge two sublists sharing any number in common?
but I am stuck in my code now.
I want to merge the sublists that share a common number,
e.g. [1,2,3]
and [3,4,5]
can merge to give [1,2,3,4,5]
as they share a common number, 3
.
In [[1,2,3],[3,4,5],[5,6]],
although [1,2,3] and [3,4,5]
share a common number, 3
,
[3,4,5]
and [5,6]
also share a common number, 5
, so I want all three of them to merge then gives
[1,2,3,4,5,6]
.
So for list, my expected result is:
[[1,2,3,4,5,6,7],[9,10,11]]
I have tried the following code but don't know what is wrong, can anyone help?
s = map(set, list)
for i, si in enumerate(s):
for j, sj in enumerate(s):
if i != j and si & sj:
s[i] = si | sj
s[j] = set()
list=[list(el) for el in s if el]
print list
>>>[[5, 6, 7], [9, 10, 11]]