合并未知数量的列表,只保留常用值

时间:2016-10-20 16:56:59

标签: python python-2.x

我想要合并 N 列表并仅保留每个列表中的值。我不知道有多少列表,所以代码必须是动态的。

a_list = [(3, -1), (3, -1), (3, 0), (4, -1), (3, 1), (5, -1), (3, 2), (6, -1), (3, 3), (7, -1), (7, -1), (3, 3), (7, 0), (4, 3), (7, 1), (5, 3), (7, 2), (6, 3), (7, 3), (7, 3)]
b_list = [(-3, 3), (-3, 3), (-3, 4), (-2, 3), (-3, 5), (-1, 3), (-3, 6), (0, 3), (-3, 7), (1, 3), (-3, 8), (2, 3), (-3, 9), (3, 3), (3, 3), (-3, 9), (3, 4), (-2, 9), (3, 5), (-1, 9), (3, 6), (0, 9), (3, 7), (1, 9), (3, 8), (2, 9), (3, 9), (3, 9)]
a = set(a_list)
b = set(b_list)
print(list(a&b))

此代码适用于已知数量的列表,但我不知道有多少列表。

注意:"未知数量的列表"意味着它取决于脚本运行的值。

编辑: N> 0

2 个答案:

答案 0 :(得分:4)

您可以使用内置的set函数intersection

print (set.intersection(*map(set, lists)))

答案 1 :(得分:2)

使用reduce

import functools
list_of_sets = [set(x) for x in list_of_lists]
intersection = functools.reduce(lambda x, y: x & y, list_of_sets)