【问题标题】:Using list comprehension to keep items not in second list使用列表推导来保持项目不在第二个列表中
【发布时间】:2017-01-08 03:34:36
【问题描述】:

我正在尝试使用列表推导从列表中删除一些项目,只保留未指定的项目。

例如,如果我有 2 个列表 a = [1,3,5,7,10]b = [2,4] 我想保留 a 中不在与 b 中的数字对应的索引处的所有项目。

现在,我尝试使用 y = [a[x] for x not in b] 但这会产生 SyntaxError。

y = [a[x] for x in b] 工作正常,只保留我想要删除的元素。

那么我该如何实现呢?顺便说一句,这是一个好方法还是我应该使用del

【问题讨论】:

  • 你是这个意思? [x for i,x in enumerate(a) if i not in b]
  • 是的,它是,不,你不应该;)
  • in 是列表解析语法的一部分,而不是 in 运算符,因此不能简单地被 not in 替换。

标签: python list list-comprehension not-operator


【解决方案1】:

您可以使用enumerate() 并在b 中查找索引:

>>> a = [1, 3, 5, 7, 10]
>>> b = [2, 4]
>>> [item for index, item in enumerate(a) if index not in b]
[1, 3, 7]

请注意,为了缩短查找时间,最好将b 作为一个set 而不是一个列表。 Lookups into sets are O(1) on average 在列表中 - O(n) 其中n 是列表的长度。

【讨论】:

    【解决方案2】:

    之后:

    y = [a[x] for x in b]
    

    只需添加:

    for x in y:
        a.remove(x)
    

    然后你会在 a 中得到一个精简列表

    【讨论】:

    • remove 删除第一次出现的元素,不一定是您要删除的元素。
    【解决方案3】:

    猜你正在寻找类似的东西:

    [ x  for x  in a if a.index(x) not in b  ] 
    

    或者,使用过滤器:

    filter(lambda x : a.index(x) not in b , a)
    

    【讨论】:

      【解决方案4】:

      试试这个就行了

         [j for i,j in enumerate(a) if i not in b ]
      

      【讨论】:

        猜你喜欢
        • 2019-10-18
        • 1970-01-01
        • 1970-01-01
        • 2023-04-06
        • 2016-04-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多