I have the following list in Python:
[[1, 2], [3, 4], [4, 6], [2, 7], [3, 9]]
I want to group them into [[1,2,7],[3,4,6,9]]
My code to do this looks like this:
l=[[1, 2], [3, 4], [4, 6], [2, 7], [3, 9]]
lf=[]
for li in l:
for lfi in lf:
if lfi.intersection(set(li)):
lfi=lfi.union(set(li))
break
else:
lf.append(set(li))
lf is my final list. I do a loop over l and lf and when I find an intersection between an element from l and another from lf, I would like to merge them (union)
But I can’t figure out why this is not working. The first to elements of the list l are being inserted with the append command, but the union is not working.
My final list lf looks like [set([1, 2]), set([3, 4])]
It seems to be something pretty basic, but I’m not familiar with sets.
I appreciate any help
Thanks
The problem is here:
You are not modifying the set. You are creating a new set which is then discarded. The original set is still in the
lfarray. Use update instead:This modifies the original set instead of creating a new one. The result after making this change: