[英]Removing duplicates from a nested list
我正在嘗試獲取一個名為new_colors
的新列表,其中只有[['orange', 'green'], ['purple', 'red']]
,從我的原始列表colors
中刪除重復項。 例如, 'orange'
在兩個不同的列表中重復兩次。
colors = [
['orange', 'green'],
['orange', 'yellow'],
['purple', 'red'],
['brown', 'red']]
這是我想出的,但它不起作用。
new_colors = []
for i in colors:
if i not in new_colors:
new_colors.append(i)
print(new_colors)
您可以定義和順序更新一個set seen
存儲元素 seen ,並與any
結合使用in
測試子列表是否有任何seen
的元素:
colors = [['orange', 'green'], ['orange', 'yellow'], ['purple', 'red'], ['brown', 'red']]
seen = set()
output = []
for sublst in colors:
if not any(x in seen for x in sublst):
output.append(sublst)
seen.update(sublst)
print(output) # [['orange', 'green'], ['purple', 'red']]
由於您的示例模棱兩可,因此我在這里提供了一種解決方案,可以在“列”上獨立跟蹤重復項。 這意味着,如果您有一個額外的['red', 'black']
,它將被保留,因為red
在第一列中是唯一的。
new_colors = []
seen = [set() for i in range(len(colors))]
for l in colors:
# check if any item was already picked
if any(e in s for e,s in zip(l,seen)):
continue
new_colors.append(l)
# update picked items
for e,s in zip(l,seen):
s.add(e)
print(new_colors)
Output:
[['orange', 'green'],
['purple', 'red']]
或多或少基於@j1-lee 的回答,您可以將整個東西包裝在一個生成器中。 迭代顏色組,並為每個顏色組生成一組。 如果當前顏色集與之前看到的所有顏色集 colors 之間存在交集,則什么也不做。 否則,產生當前組並更新之前看到的 colors 的集合:
colors = [
['orange', 'green'],
['orange', 'yellow'],
['purple', 'red'],
['brown', 'red']
]
def to_filtered(groups):
seen = set()
for current_set, current_group in zip(map(set, groups), groups):
if not seen & current_set:
yield current_group
seen |= current_set
print(list(to_filtered(colors)))
Output:
[['orange', 'green'], ['purple', 'red']]
你可以試試這個
colors = [
['orange', 'green'],
['orange', 'yellow'],
['purple', 'red'],
['brown', 'red']]
new_colors = []
isUnique = True
for pair in colors:
unique_colors = [new_color for new_pair in new_colors for new_color in new_pair]
for color in pair:
if color in unique_colors:
isUnique = False
break
if isUnique == True:
new_colors.append(pair)
isUnique = True
print(new_colors)
因此,首先我在這里聲明一個附加變量isUnique
作為標志,並使用外部 for 循環內的新列表unique_colors
,它是new_colors
列表的扁平版本,每次將新的唯一顏色pair
添加到new_colors
列表時都會更新。
然后在內部 for 循環中,對當前pair
的每種顏色進行檢查。 在這里,如果當前pair
的任何color
與unique_colors
列表的任何顏色匹配, isUnique
將設置為False
,並且內部循環將中斷。
之后isUnique
將被檢查,如果它是True
那么當前pair
將被添加到new_colors
並且最后isUnique
將被設置為True
用於下一次迭代。
Output: [['orange', 'green'], ['purple', 'red']]
您必須嵌套 for 循環來迭代元素而不是子列表
colors = [
['orange', 'green'],
['orange', 'yellow'],
['purple', 'red'],
['brown', 'red']
]
new_colors = []
for i in colors:
for j in i:
if j not in new_colors:
new_colors.append(j)
print(new_colors)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.