如何将多个列表合并为 1,但仅合并所有初始列表中的那些元素?
How to merge multiple lists into 1 but only those elements that were in all of the initial lists?
我需要合并 5 个列表,其中任何列表都可以这样为空,以便只有所有 5 个初始列表中的项目都包含在新形成的列表中。
for filter in filters:
if filter == 'M':
filtered1 = [] # imagine that this is filled
if filter == 'V':
filtered2 = [] # imagine that this is filled
if filter == 'S':
filtered3 = [] # imagine that this is filled
if filter == 'O':
filtered4 = [] # imagine that this is filled
if filter == 'C':
filtered5 = [] # imagine that this is filled
filtered = [] # merge all 5 lists from above
所以现在我需要制作一个列表,其中包含来自所有过滤列表 1-5 的合并数据。我应该怎么做?
给定一些列表 xs1
, ..., xs5
:
xss = [xs1, xs2, xs3, xs4, xs5]
sets = [set(xs) for xs in xss]
merged = set.intersection(*sets)
这有属性,merged
可以任意顺序。
f1, f2, f3, f4, f5 = [1], [], [2, 5], [4, 1], [3]
only_merge = [*f1, *f2, *f3, *f4, *f5]
print("Only merge: ", only_merge)
merge_and_sort = sorted([*f1, *f2, *f3, *f4, *f5])
print("Merge and sort: ", merge_and_sort)
merge_and_unique_and_sort = list({*f1, *f2, *f3, *f4, *f5})
print("Merge, unique and sort: ", merge_and_unique_and_sort)
输出:
Only merge: [1, 2, 5, 4, 1, 3]
Merge and sort: [1, 1, 2, 3, 4, 5]
Merge, unique and sort: [1, 2, 3, 4, 5]
这是最经典的解决方案
filtered = filter1 + filter2 + filter3 + filter4 + filter5
您将一个列表添加到另一个列表,依此类推...
因此,如果 filter1 为 ['a'、'b'],filter3 为 ['c'、'd'],filter4 为 ['e'],
那么你会得到:
filtered = ['a', 'b', 'c', 'd', 'e']
我需要合并 5 个列表,其中任何列表都可以这样为空,以便只有所有 5 个初始列表中的项目都包含在新形成的列表中。
for filter in filters:
if filter == 'M':
filtered1 = [] # imagine that this is filled
if filter == 'V':
filtered2 = [] # imagine that this is filled
if filter == 'S':
filtered3 = [] # imagine that this is filled
if filter == 'O':
filtered4 = [] # imagine that this is filled
if filter == 'C':
filtered5 = [] # imagine that this is filled
filtered = [] # merge all 5 lists from above
所以现在我需要制作一个列表,其中包含来自所有过滤列表 1-5 的合并数据。我应该怎么做?
给定一些列表 xs1
, ..., xs5
:
xss = [xs1, xs2, xs3, xs4, xs5]
sets = [set(xs) for xs in xss]
merged = set.intersection(*sets)
这有属性,merged
可以任意顺序。
f1, f2, f3, f4, f5 = [1], [], [2, 5], [4, 1], [3]
only_merge = [*f1, *f2, *f3, *f4, *f5]
print("Only merge: ", only_merge)
merge_and_sort = sorted([*f1, *f2, *f3, *f4, *f5])
print("Merge and sort: ", merge_and_sort)
merge_and_unique_and_sort = list({*f1, *f2, *f3, *f4, *f5})
print("Merge, unique and sort: ", merge_and_unique_and_sort)
输出:
Only merge: [1, 2, 5, 4, 1, 3]
Merge and sort: [1, 1, 2, 3, 4, 5]
Merge, unique and sort: [1, 2, 3, 4, 5]
这是最经典的解决方案
filtered = filter1 + filter2 + filter3 + filter4 + filter5
您将一个列表添加到另一个列表,依此类推...
因此,如果 filter1 为 ['a'、'b'],filter3 为 ['c'、'd'],filter4 为 ['e'], 那么你会得到:
filtered = ['a', 'b', 'c', 'd', 'e']