问题
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?
回答1:
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))
回答2:
In one liner:
>>> reduce(set.intersection, x[1:], set(x[0]))
set([3, 4])
回答3:
def f(a, b):
return list(set(a).intersection(set(b)))
reduce(f, x)
回答4:
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])
>>>
来源:https://stackoverflow.com/questions/1723072/find-and-keep-duplicates-of-sublist-in-python