Crossing N-many lists in python

What is the easiest way to take the intersection of N-many lists in python?

If I have two lists a and b, I know what I can do:

a = set(a) b = set(b) intersect = a.intersection(b) 

but I want to do something like a, b and c and d and ... for an arbitrary set of lists (ideally without converting to a set first, but if this is the easiest / most efficient way, I can deal with that.)

those. I want to write an intersect (* args) function that will do this for arbitrarily many sets efficiently. What is the easiest way to do this?

EDIT: my own solution is decreasing (set.intersection, [a, b, c]) - is that good?

thanks.

+6
python list numpy scipy
source share
3 answers

This works for 1 or more lists. The case with lists 0 is not so simple because it will have to return a set containing all possible values.

 def intersection(first, *others): return set(first).intersection(*others) 
+13
source share

This works with 1 or more lists and does not use several parameters:

 >>> def intersection(*listas): ... return set(listas[0]).intersection(*listas[1:]) ... >>> intersection([1,2,3,4],[4,5,6],[2,4,5],[1,4,8]) set([4]) >>> intersection([1,2,3,4]) set([1, 2, 3, 4]) >>> 

Not sure if this is better than the other answers. Anyway.

+2
source share
 lists = [[5,4,3], [4,2], [6,2,3,4]] try: # the following line makes one intersection too much, but I don't think # this hurts performance noticably. intersected = set(lists[0]).intersection(*lists) except ValueError: # no lists[0] intersected = set() print intersected # set([4]) 

Sets can be intersected with any iterable, there is no need to first convert it to a set.

+2
source share

All Articles