如何找到列表列表中的公共元素? [英] How to find common elements in list of lists?

查看:128
本文介绍了如何找到列表列表中的公共元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想弄清楚如何比较n个列表来找到共同的元素。
例如:

I'm trying to figure out how to compare an n number of lists to find the common elements. For example:

p=[ [1,2,3],
    [1,9,9],
      ..
      ..
    [1,2,4]

>> print common(p)
>> [1]

现在如果我知道元素的数量,我可以做比较:

Now if I know the number of elements I can do comparions like:

for a in b:
  for c in d:
    for x in y:
...

但是如果我不知道有多少元素p,它不工作。我看过这个比较两个列表的解决方案
http://stackoverflow.com/a/1388864/1320800< a>

but that wont work if I don't know how many elements p has. I've looked at this solution that compares two lists http://stackoverflow.com/a/1388864/1320800

但是花了4个小时试图找到一个递归的方法,一个解决方案仍然逃避我,所以任何帮助将高度赞赏!

but after spending 4 hrs trying to figure a way to make that recursive, a solution still eludes me so any help would be highly appreciated!

推荐答案

您正在查找所有子列表的集合交集,并且您应该用于集合操作的数据类型是一组:

You are looking for the set intersection of all the sublists, and the data type you should use for set operations is a set:

result = set(p[0])
for s in p[1:]:
    result.intersection_update(s)
print result

这篇关于如何找到列表列表中的公共元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆