I am playing with python and am able to get the intersection of two lists:
result = set(a).intersection(b)
Now if d
is a list containing a
and b
and a third element c
, is there an built-in function for finding the intersection of all the three lists inside d
? So for instance,
d = [[1,2,3,4], [2,3,4], [3,4,5,6,7]]
then the result should be
[3,4]
@user3917838
Nice and simple but needs some casting to make it work and give a list as a result. It should look like:
list(reduce(set.intersection, [set(item) for item in d ]))
where:
d = [[1,2,3,4], [2,3,4], [3,4,5,6,7]]
And result is:
[3, 4]
At least in Python 3.4
Lambda reduce.
for 2.4, you can just define an intersection function.
for newer versions of python:
the intersection method takes an arbitrary amount of arguments
alternatively, you can intersect the first set with itself to avoid slicing the list and making a copy:
I'm not really sure which would be more efficient and have a feeling that it would depend on the size of the
d[0]
and the size of the list unless python has an inbuilt check for it likein the intersection method.