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

时间:2010-01-22 09:36:47

标签: python list

我有一个任意数量的列表列表,例如:

[[1,2,3], [3,4,5], [5,6,7], [7,8,9]]

现在我想要一个包含多个列表中所有元素的列表:

[3,5,7]

我该怎么做?

谢谢!

11 个答案:

答案 0 :(得分:12)

与手工操作相同:

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)

顺便说一句,这是一些人正在寻找的一个班轮(不计入导入)(应该比其他方法效率低)

from itertools import *
reduce(set.union, (starmap(set.intersection, combinations(map(set, ll), 2))))

答案 1 :(得分:5)

最干净的方法可能是使用reduce:

def findCommon(L):
    def R(a, b, seen=set()):
        a.update(b & seen)
        seen.update(b)
        return a
    return reduce(R, map(set, L), set())

result = findCommon([[1,2,3], [3,4,5], [5,6,7], [7,8,9]])

结果是一个集合,但如果您确实需要列表,则只需list(result)

答案 2 :(得分:5)

另一个简单的解决方案(一行):

 set.intersection(*[set(list) for list in list_of_lists])

答案 3 :(得分:3)

参考:http://docs.python.org/library/stdtypes.html#set

#!/usr/bin/python

ll = [[1,2,3], [3,4,5], [5,6,7], [7,8,9]]
ls = [set(l) for l in ll]

su = ls[0]  #union
ssd = ls[0] #symmetric_difference
for s in ls[1:]:
  su = su.union(s)
  ssd = ssd.symmetric_difference(s)

result = su.difference(ssd)
print list(result)

=>

[3, 5, 7]

修改并采用FP,

ll = [[1,2,3], [3,4,5], [5,6,7], [7,8,9]]

u = reduce(set.union, map(set, ll))
sd = reduce(set.symmetric_difference, map(set, ll))
print u - sd

=>

[3, 5, 7]

答案 4 :(得分:1)

您可以使用字典来获取每个

的计数
from collections import defaultdict

init_list = [[1,2,3], [3,4,5], [5,6,7], [7,8,9]]
#defaultdict, every new key will have a int(0) as default value
d = defaultdict(int)
for values in init_list:
  #Transform each list in a set to avoid false positives like [[1,1],[2,2]]
  for v in set(values):
    d[v] += 1

#Get only the ones that are more than once
final_list = [ value for value,number in d.items() if number > 1 ]

答案 5 :(得分:1)

试试这个:

data = [[1,2,3], [3,4,5], [5,6,7], [7,8,9], [1,2,3]]

res = set()

for i in data:
    for j in data:
        if i is not j:
            res |= set(i) & set(j)

print res

答案 6 :(得分:1)

>>> sets = [[1,2,3], [3,4,5], [5,6,7], [7,8,9]]
>>> seen = set()
>>> duplicates = set()
>>> 
>>> for subset in map(set, sets) :
...     duplicates |= (subset & seen)
...     seen |= subset
... 
>>> print(duplicates)
set([3, 5, 7])
>>> 

我尝试使用map / reduce进行单行回答,但还不太明白。

答案 7 :(得分:0)

l=[[1,2,3], [3,4,5], [5,6,7], [7,8,9]]
d={}
for x in l:
    for y in x:
        if not d.has_key(y):
            d[y]=0
        d[y]+=1
[x for x,y in d.iteritems() if y>1]

答案 8 :(得分:0)

这是我的去处:

seen = set()
result = set()
for s in map(set, [[1,2,3], [3,4,5], [5,6,7], [7,8,9]]):
    result.update(s & seen)
    seen.update(s)
print result

打印:

set([3, 5, 7])

答案 9 :(得分:-1)

您可以使用套装,参见http://docs.python.org/library/stdtypes.html#set

答案 10 :(得分:-2)

展平,排序,1循环比较

之前和之后的数字