Find (and keep) duplicates of sublist in python
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])
def f(a, b):
return list(set(a).intersection(set(b)))
reduce(f, x)
Just another way of solving, almost same as nadia but without using reduce, and i use map:
>>> x = [ [1, 2, 3, 4], [3, 4, 6, 7], [2, 3, 4, 6, 7]]
>>> set.intersection(*map(set,x))
set([3, 4])
>>>
精彩评论