我需要合并 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 的合并資料創建一個串列。我該怎么做?
uj5u.com熱心網友回復:
給定一些串列xs1, ..., xs5:
xss = [xs1, xs2, xs3, xs4, xs5]
sets = [set(xs) for xs in xss]
merged = set.intersection(*sets)
這具有merged可以按任何順序排列的屬性。
uj5u.com熱心網友回復:
這是最經典的解決方案。
filtered = filter1 filter2 filter3 filter4 filter5
發生的情況是您將一個串列添加到另一個串列中,依此類推...
所以如果 filter1 是 ['a', 'b'] 并且 filter3 是 ['c', 'd'] 并且 filter4 是 ['e'],那么你會得到:
filtered = ['a', 'b', 'c', 'd', 'e']
uj5u.com熱心網友回復:
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]
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/396290.html
