I have a list of lists (sublist) that contains numbers and I only want to keep those exists in all (sub)lists.
Example:
x = [ [1, 2, 3, 4], [3, 4, 6, 7], [2, 3, 4, 6, 7]]
output => [3, 4]
How can I do this?
common = set(x[0])
for l in x[1:]:
common &= set(l)
print list(common)
or:
import operator
print reduce(operator.iand, map(set, x))
In one liner:
>>> reduce(set.intersection, x[1:], set(x[0]))
set([3, 4])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With