【问题标题】:python matching 2 list of lists and removing matchpython匹配2个列表并删除匹配项
【发布时间】:2017-05-20 07:55:47
【问题描述】:

我想从 list2 中删除列表中与 list1 中的第三项匹配的任何列表项。我目前正在尝试为 list1 中的每个项目循环 list2 并根据第三个字段删除。

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

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

【问题讨论】:

  • 与其修改list2,不如新建一个list? new_list = [item for item in list2 if item not in list1] 如果你愿意,你也可以分配给list2
  • remove from list2 any list item in the list that matches the third item in list1
  • @sytech 你试过运行它吗?
  • 这并不是完整的解决方案。只是想问 OP 创建一个新列表是否可以接受。 @roganjosh 你可以在下面看到我提出的解决方案。
  • @sytech 啊,因为它是一个有效的列表理解,我假设你认为它会给出预期的输出:)

标签: python algorithm list


【解决方案1】:

我建议创建一个新列表。您还可以为 list1 中的所有第三项创建一个中间 third_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]]

或作为列表组合

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

【讨论】:

  • 完美运行。花了一点时间,因为 list1 是 170 个列表条目,而 list2 是 68,478 个列表条目。
【解决方案2】:

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

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 ]

如果您不想要一个新列表,但真的想从 list2 中删除,那么:

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

【讨论】:

    【解决方案3】:

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

    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)
    

    如果两个列表的长度相同,则这样做:

    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]]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-27
      • 2022-01-18
      相关资源
      最近更新 更多