在python中查找(并保留)子列表的副本
我有一个包含数字的列表(子列表),我只想保留所有(子)列表中存在的数字 例如:在python中查找(并保留)子列表的副本,python,list,duplicates,sublist,Python,List,Duplicates,Sublist,我有一个包含数字的列表(子列表),我只想保留所有(子)列表中存在的数字 例如: x = [ [1, 2, 3, 4], [3, 4, 6, 7], [2, 3, 4, 6, 7]] output => [3, 4] 我该怎么做 common = set(x[0]) for l in x[1:]: common &= set(l) print list(common) 或: 一行: >>> reduce(set.intersection, x[1:],
x = [ [1, 2, 3, 4], [3, 4, 6, 7], [2, 3, 4, 6, 7]]
output => [3, 4]
我该怎么做
common = set(x[0])
for l in x[1:]:
common &= set(l)
print list(common)
或:
一行:
>>> reduce(set.intersection, x[1:], set(x[0]))
set([3, 4])
只是另一种解决方法,几乎与nadia相同,但不使用reduce,我使用map:
>>> x = [ [1, 2, 3, 4], [3, 4, 6, 7], [2, 3, 4, 6, 7]]
>>> set.intersection(*map(set,x))
set([3, 4])
>>>
我最初是从set()开始的,现在已经修好了。是的,我发布了一个答案,修改了你的答案并成功了,但当我回来的时候,你编辑了它。可悲的是,stackoverflow不会让我+1你,因为我投了更高的票,然后取消了我的投票。回答得很好!或列表(reduce(set.intersection,x[1:],set(x[0]))
def f(a, b):
return list(set(a).intersection(set(b)))
reduce(f, x)
>>> x = [ [1, 2, 3, 4], [3, 4, 6, 7], [2, 3, 4, 6, 7]]
>>> set.intersection(*map(set,x))
set([3, 4])
>>>