Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中查找(并保留)子列表的副本_Python_List_Duplicates_Sublist - Fatal编程技术网

在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])
>>>