这是我的两个清单。
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]]
我的输出应为以下内容;
[[1, 2], [4], [5, 6, 2], [1, 2], [3], [4]]
如何获得此输出?
先感谢您
您将必须将列表转换为元组列表,然后使用交集。请注意,下面的解决方案可能具有不同顺序的元素,并且由于我使用的是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]]
您也可以将交叉点保存在变量中并获取最终列表,如果需要排序,则需要重复:
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]]
和交叉点,以防万一您感兴趣。
In [6]: print intersection set([(1, 2), (5, 6, 2), (3,), (4,)])
这对于大型列表将非常有效,但是如果列表较小,请通过@timegb探索其他解决方案(对于较长的列表,其解决方案将是非常不理想的)