List Comprehension And Intersection Problem
list(set(a[0]) & set(a[1]) & set(a[2]) & set(a[3]) & set(a[4])) Does anyone know how to write this in a way such that we dont need to know apriori how many lists w
Solution 1:
As long as you have at least one set, you can do this:
list(set(a[0]).intersection(*a[1:]))
If there might be no sets, you have to decide for yourself what the "intersection of no sets" actually should mean in your application. If you want the empty set:
list(set(*a[:1]).intersection(*a[1:]))
Solution 2:
I think it's worth noting, at least to improve one's general programming understanding, that what you want to do can be described as mapping and then reducing or folding. Specifically, you want to map set
over a
and then fold &
over the result.
I'm not a Python expert, but it can be done like this in Python:
from functools import reduce
a = [
[1,2,3],
[1,2,3,4],
[1,2,4,5],
[1,2,3,5],
]
intersection = lambda x, y: x & y
mapped = list(map(set, a))
reduced = reduce(intersection, mapped)
Note that this implementation requires a
to be non-empty.
Post a Comment for "List Comprehension And Intersection Problem"