Im struggling with something that is probably not complicated. I have a list of lists and I want to Group the elements together if they share any common elements:
For example first list [1,2] is grouped with third list [3,4] because they "overlap" through second list [2,3]
There must be some easier way than:
a = [[1,2],
[2,3],
[3,4],
[7,8]]
newlist = []
for count, pair in enumerate(a):
if count==0:
newlist.append(pair)
else:
for index, group in enumerate(newlist):
if not set(group).isdisjoint(pair):
newlist[index].extend(pair)
else:
newlist.append(pair)
newlist = [set(group) for group in newlist]
newlist
[{1, 2, 3, 4}, {8, 7}]