Python-列表的两个列表的交集 [英] Python - Intersection of two lists of lists
问题描述
这是我的两个列表;
k = [[1, 2], [4], [5, 6, 2], [1, 2], [3], [4], [5,9]]
kDash = [[1, 2], [4], [5, 6, 2], [1, 2], [3], [4], [5,6], [1,2]]
我的输出应为以下内容;
My output should be the following;
[[1, 2], [4], [5, 6, 2], [1, 2], [3], [4]]
如何获得此输出?
先谢谢您
推荐答案
您将不得不将列表转换为元组列表,然后使用交集.请注意,下面的解决方案可能具有不同顺序的元素,并且由于我使用的是set,因此显然不会存在重复项.
You will have to convert the lists to list of tuples, and then use the intersection. Note that below solution may have elements in a different order, and duplicates will obviously not be there, since I'm using set.
In [1]: l1 = [[1, 2], [4], [5, 6, 2], [1, 2], [3], [4], [5,9]]
In [2]: l2 = [[1, 2], [4], [5, 6, 2], [1, 2], [3], [4], [5,6], [1,2]]
In [3]: [list(x) for x in set(tuple(x) for x in l1).intersection(set(tuple(x) for x in l2))]
Out[3]: [[1, 2], [5, 6, 2], [3], [4]]
您也可以将交叉点保存在变量中并获取最终列表,如果要订购,则必须重复:
You can alternatively save the intersection in a variable and get the final list, if order, duplicates are necessary:
In [4]: intersection = set(tuple(x) for x in l1).intersection(set(tuple(x) for x in l2))
In [5]: [x for x in l1 if tuple(x) in intersection]
Out[5]: [[1, 2], [4], [5, 6, 2], [1, 2], [3], [4]]
还有交叉路口,以防万一您感兴趣.
And the intersection, just in case if you are interested.
In [6]: print intersection
set([(1, 2), (5, 6, 2), (3,), (4,)])
这对于大型列表将非常有效,但是如果列表较小,请通过@timegb探索其他解决方案(对于较长的列表,其解决方案将不是最佳选择)
This will work pretty well for large lists, but if the lists are small, do explore the other solution by @timegb (whose solution will be highly unoptimal for longer lists)
这篇关于Python-列表的两个列表的交集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!