【问题标题】:How could I compare lists in lists?我如何比较列表中的列表?
【发布时间】:2020-02-23 22:11:24
【问题描述】:

我有两个列表:

a = [[7, 2, -1, -6, -100], [-1, 0, 5, 2, 3], [0, 0, 1, 0, 0]]
b = [[1],[2],[0,0,1,0,0]]

我用:

result = filter(lambda x: x not in b, a)

我的预期结果应该是:

[[7, 2, -1, -6, -100], [-1, 0, 5, 2, 3]]

为什么我得到:

[[7, 2, -1, -6, -100], [-1, 0, 5, 2, 3], [0, 0, 1, 0, 0]]

我希望有人可以帮助我解决这个问题!谢谢:)

【问题讨论】:

  • 我得到了你的预期结果,我看不出上面的代码有什么问题
  • 您的代码运行良好。 list(filter(lambda x: x not in b, a))

标签: python list lambda filter


【解决方案1】:

您的代码按预期工作,您可能会打印错误的变量。

a = [[7, 2, -1, -6, -100], [-1, 0, 5, 2, 3], [0, 0, 1, 0, 0]]
b = [[1],[2],[0,0,1,0,0]]
result = list(filter(lambda x: x not in b, a))
print(result)

你得到

[[7, 2, -1, -6, -100], [-1, 0, 5, 2, 3]]

但是,如果您使用该过滤器,则会就地过滤并修改您的变量 a,这是一个错误。

print(a)

你得到

[[7, 2, -1, -6, -100], [-1, 0, 5, 2, 3], [0, 0, 1, 0, 0]]

注意

在python 3中,过滤器返回一个生成器,您需要将其耗尽才能获得所需的输出,一种方法是:

list(filter(...))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-12
    • 2021-01-19
    • 2023-01-12
    • 2011-08-31
    • 1970-01-01
    • 2022-12-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多