Python:在多个列表中查找相同的项目

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