【问题标题】:How to remove the items in a list that are in a second list in python?python - 如何删除列表中第二个列表中的项目?
【发布时间】:2019-11-13 17:02:14
【问题描述】:

我有一个列表列表和另一个列表,我想从第二个列表中的列表列表中删除所有项目。

first = [[1,3,2,4],[1,2],[3,4,2,5,1]]
to_remove = [1,2]

一般情况下我将如何解决这个问题?

这里也有类似的问题,但没有任何帮助。

【问题讨论】:

  • 您需要向我们提供您尝试使用的代码
  • 您要删除项目的所有实例吗?如果 first = [[1,1,3,2,4],[1,2],[3,4,2,5,1]] 那么输出是否不同?

标签: python python-3.x list sublist


【解决方案1】:

result = []
for l in first:
    tmp = []
    for e in l:
        if e not in to_remove:
            tmp.append(e)
    result.append(tmp)

print(result)

如果元素在 to_remove 列表中,则此代码循环遍历所有列表和每个列表的所有元素,它会跳过它并转到下一个。 因此,如果您有多个实例,它将删除它

最好的尊重

【讨论】:

  • 你怎么能以 comprehension 风格尝试这个?
  • @igorkf 是的,当然result = [[e for e in l if e not in to_remove] for l in first] :)
【解决方案2】:

使用sets 的优雅解决方案:

first = [[1,3,2,4],[1,2],[3,4,2,5,1]]
to_remove = [1,2]
result = [list(set(x).difference(to_remove)) for x in first]
result
[[3, 4], [], [3, 4, 5]]

【讨论】:

    猜你喜欢
    • 2012-10-26
    • 2011-05-24
    • 2015-10-06
    • 2022-12-20
    • 1970-01-01
    • 2023-01-24
    • 1970-01-01
    • 1970-01-01
    • 2021-07-19
    相关资源
    最近更新 更多