Find (and keep) duplicates of sublist in python

蓝咒 提交于 2020-01-10 19:50:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!