繁体   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