2

Ok, so I want/need to use the "|: operator

Say I have a list:

list = [{1,2,3},{2,3,4},{3,4,5},{4,5,6}]

I need to find the intersection of the list without using: set.intersection(*L)

Ideally I'd like to use a function with a for loop (or nested for loops) to get return the intersections of all of the sets in the list:

isIntersction(L) = {1,2,3,4,5,6}

Thanks

3
  • 2
    That's not the intersection, it's the union Commented Jul 4, 2013 at 3:34
  • 1
    Why do you want to "ideally us a function with a for loop"? Does your homework say you have to? because there's nothing "ideal" about doing it that way Commented Jul 4, 2013 at 3:37
  • 1) yes, it is a union, my bad, and 2, it needs to be in the form: def isUnion(L): union = {} for i in L: (code here) return variable Commented Jul 4, 2013 at 8:43

3 Answers 3

3
>>> L=[{1,2,3},{2,3,4},{3,4,5},{4,5,6}]
>>> from itertools import chain
>>> set(chain.from_iterable(L))
{1, 2, 3, 4, 5, 6}
Sign up to request clarification or add additional context in comments.

Comments

1

Try this, using list comprehension

list = [{1,2,3},{2,3,4},{3,4,5},{4,5,6}]
b = []
[b.append(x) for c in list for x in c if x not in b]
print b # or set(b)

Output:

[1, 2, 3, 4, 5, 6]

If you are keen on having the output as a set, try this:

b = set([])
[b.add(x) for c in list for x in c if x not in b]
print b

Output:

set([1, 2, 3, 4, 5, 6]) #or {1, 2, 3, 4, 5, 6}

If you want a function try this:

def Union(L):
    b = []
    [b.append(x) for c in L for x in c if x not in b]
    return set(b)

1 Comment

This is exactly what I was looking for. I changed it around to the long form: def myUnion(L): union = [] for i in L: for j in i: if i not in union: union.append(i) return set(union)
1

You can use the built-in reduce:

>>> L = [{1,2,3},{2,3,4},{3,4,5},{4,5,6}]
>>> reduce(set.union, L, set())
set([1, 2, 3, 4, 5, 6])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.