python匹配2个列表列表并删除匹配项

python匹配2个列表列表并删除匹配项,python,algorithm,list,Python,Algorithm,List,我想从列表2中删除列表中与列表1中第三项匹配的任何列表项。目前,我正在尝试为列表1中的每个项目遍历列表2,并基于第三个字段删除 list1: [[1,2,3],[4,5,6],[7,8,9]] list2: [[-1,-2,3],[-4,-5,-6],[-7,-8,9],[1,2,8]] final list2: [[-4,-5,-6],[1,2,8]] 我的伪代码: for item1 in list1: for item2 in list2: if item1[

我想从列表2中删除列表中与列表1中第三项匹配的任何列表项。目前,我正在尝试为列表1中的每个项目遍历列表2,并基于第三个字段删除

list1: [[1,2,3],[4,5,6],[7,8,9]]

list2: [[-1,-2,3],[-4,-5,-6],[-7,-8,9],[1,2,8]]

final list2: [[-4,-5,-6],[1,2,8]]
我的伪代码:

for item1 in list1:
    for item2 in list2:
        if item1[2] == item2[2]:
            remove item2[2] from list2

我尝试了一些使用集合和/或元组的示例技术,但它们都基于从一个列表中删除重复项;与基于单独列表中的一个字段删除列表中的项目不同。

我建议创建一个新列表。您还可以为列表1中的所有第三项创建一个中间项
third\u items
集,以供检查,而不是在每次迭代中探测每个元素

list1 = [[1,2,3],[4,5,6],[7,8,9]]
list2 = [[-1,-2,3],[-4,-5,-6],[-7,-8,9],[1,2,8]]

third_items = set(sublist[2] for sublist in list1)
new_list = []
for sublist in list2:
    if sublist[2] not in third_items:
        new_list.append(sublist)
print(new_list)
输出:

[[-4, -5, -6], [1, 2, 8]]
或者作为列表comp

third_items = set(sublist[2] for sublist in list1)
new_list = [sublist for sublist in list2 if sublist[2] not in third_items]

您可以使用列表理解在一行中执行此操作:

result = [ (a) for a in list2 if a[2] not in [ (b[2]) for b in list1 ] ]
这不一定是最有效的方法,但可能是最简洁的方法。如果您处理的是大型列表,您可能希望首先提取查找。例如:

lookup = [ (b[2]) for b in list1 ]
result = [ (a) for a in list2 if a[2] not in lookup ]
如果您不想要新列表,但确实想从列表2中删除,则:

lookup = [ (b[2]) for b in list1 ]
[ list2.remove(a) for a in list2 if a[2] in lookup ]

如果只想比较两个列表中的相应元素,则以下操作将起作用:

list1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
list2 = [[-1, -2, 3], [-4, -5, -6], [-7, -8, 9], [1, 2, 8]]

list3 = []

for index, item in enumerate(list2):
    if index < len(list1):
        if item[2] != list1[index][2]:
            list3.append(item)
    else:
        list3.append(item)

与其修改列表2,为什么不创建一个新列表
new_list=[item for item in list2 if item not in list1]
如果您愿意,也可以将任务分配给
list2
从列表2中删除与列表1中第三项匹配的列表项。
@sytech是否尝试运行该任务?这并不是完整的解决方案。只是试着问OP创建一个新列表是否可以接受@roganjosh您可以在下面看到我建议的解决方案。@sytech啊,因为它是一个有效的列表理解,我假设您认为它会给出预期的输出:)工作得很好。花了一点时间,因为list1是170个列表条目,list2是68478个列表条目。
list1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 2, 3]]
list2 = [[-1, -2, 3], [-4, -5, -6], [-7, -8, 9], [1, 2, 8]]

if len(list1) == len(list2):
    list3 = [x for i, x in enumerate(list2) if x[2] != list1[i][2]]