簡體   English   中英

比較兩個列表中的元素,如果匹配則刪除元素。 python

[英]Comparing elements in two lists and removing elements if match. python

需要將列表元素相互比較,如果相同,則將其刪除。

list_1 = [1,2,3,4]
list_2 = [1,2,5,3]
>>>>>>
list_1 = [3,4]
list_2 = [5,3]

嘗試:

list_1 = [1, 2, 3, 4]
list_2 = [1, 2, 5, 3]

list_1[:], list_2[:] = zip(*((a, b) for a, b in zip(list_1, list_2) if a != b))

print(list_1)
print(list_2)

印刷:

[3, 4]
[5, 3]

為此,您將不得不使用嵌套循環,在本例中是嵌套的 for 循環和 if 語句。 例如

list_1 = [1,2,3,4]
list_2 = [3,4]
for j in list_2:
    for i in list_1:
        if i == j:
            list_1.remove(i)
print(list_1)

這將打印 output [1,2]此方法逐一遍歷每個數字,並將其與另一個列表中的數字進行比較,如果找到匹配項,則將其從主列表中刪除。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM