Using set in Python inside a loop

Posted by user210481 on Stack Overflow See other posts from Stack Overflow or by user210481
Published on 2010-03-25T21:53:26Z Indexed on 2010/03/25 22:03 UTC
Read the original article Hit count: 316

Filed under:
|

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,7]]

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

© Stack Overflow or respective owner

Related posts about python

Related posts about dataset