简体   繁体   English

在python中查找(并保留)子列表的重复项

[英]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: 只是另一种解决方式,几乎与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])
>>>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM