Python:在多个列表中查找相同的项目 [英] Python: Find identical items in multiple lists
本文介绍了Python:在多个列表中查找相同的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个任意数量的列表,例如:
I have a list of an arbitrary number of lists, for instance:
[[1,2,3], [3,4,5], [5,6,7], [7,8,9]]
现在,我想要一个包含不止一个列表中存在的所有元素的列表:
Now I would like a list containing all elements that are present in more than one list:
[3,5,7]
我该怎么做?
谢谢!
推荐答案
与手工操作相同的方式:
The same way as you'd do it by hand:
seen = set()
repeated = set()
for l in list_of_lists:
for i in set(l):
if i in seen:
repeated.add(i)
else:
seen.add(i)
顺便说一句,这是一些人正在寻找的一种班轮(不计入进口额)(应该比另一种方式效率低)
By the way, here's the one liner (without counting the import) that some people were seeking (should be less efficient than the other approach)
from itertools import *
reduce(set.union, (starmap(set.intersection, combinations(map(set, ll), 2))))
这篇关于Python:在多个列表中查找相同的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文