合并未知数量的列表,只保留共同的值
Combine unknown amount of lists, keep only common values
我想合并 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))
此代码非常适用于已知数量的列表,但我不知道有多少列表。
注意:"Unknown number of lists" 表示它取决于脚本 运行 的值。
编辑:N > 0
使用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)
您可以使用内置的 set
函数 intersection
:
print (set.intersection(*map(set, lists)))
我想合并 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))
此代码非常适用于已知数量的列表,但我不知道有多少列表。
注意:"Unknown number of lists" 表示它取决于脚本 运行 的值。
编辑:N > 0
使用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)
您可以使用内置的 set
函数 intersection
:
print (set.intersection(*map(set, lists)))