【问题标题】:Remove list from list in Python [duplicate]从Python列表中删除列表[重复]
【发布时间】:2012-07-11 04:27:43
【问题描述】:

可能重复:
Get difference from two lists in Python

执行此操作的简化方法是什么?我一直在自己尝试,我无法弄清楚。 列表 a 和列表 b,新列表应该包含仅在列表 a 中的项目。所以:

a = apple, carrot, lemon
b = pineapple, apple, tomato
new_list = carrot, lemon

我尝试编写代码,但每次它总是将整个列表返回给我。

【问题讨论】:

    标签: python list python-2.7


    【解决方案1】:

    你可能想要这个:

    a = ["apple", "carrot", "lemon"]
    b = ["pineapple", "apple", "tomato"]
    
    new_list = [x for x in a if (x not in b)]
    
    print new_list
    

    【讨论】:

      【解决方案2】:

      您可以使用set

      # Assume a, b are Python lists
      
      # Create sets of a,b
      setA = set(a)
      setB = set(b)
      
      # Get new set with elements that are only in a but not in b
      onlyInA = setA.difference(b)
      

      更新
      正如 iurisilvio 和 mgilson 所指出的,这种方法只有在 ab 不包含重复项并且元素的顺序无关紧要时才有效。

      【讨论】:

      • 我想这是要走的路,但如果它有重复的字符串,它会更改列表。
      • @iurisilvio:你是对的。仅当ab 仅包含唯一条目时,此方法才有效。在这种情况下,无论如何将set 用于a,b 会更有意义。但这可能是最快的方法。
      • 如果物品的顺序很重要,它也不起作用,但这里可能不是这种情况(我+1)
      • 我认为bset 的转换是没有必要的。您也可以使用原始的list 执行差异。
      • @rlar 是正确的,我发现也是如此。
      【解决方案3】:

      如何使用 sets(或内置的 set,因为 Sets 在 2.6 中已被弃用)?

      from sets import Set
      a = Set(['apple', 'carrot', 'lemon'])
      b = Set(['pineapple','apple','tomato'])
      new_set =  a.difference(b)
      print new_set
      

      给出输出

      Set(['carrot', 'lemon'])
      

      【讨论】:

      • 为什么不使用内置的set
      • 我从python docs 的示例中得到了这一点,但我不确定他们为什么这样做,有什么想法吗?
      • sets 自 Python v2.6 起已弃用(请参阅 docs.python.org/library/sets.html
      • 我认为 sets 模块在内置 set 之前就已经存在了。现在它主要留在那里是为了向后兼容。
      【解决方案4】:

      您可以使用list comprehension 编写此代码,它可以非常准确地告诉我们哪些元素需要以new_list 结尾:

      a = ['apple', 'carrot', 'lemon']
      b = ['pineapple', 'apple', 'tomato']
      
      # This gives us: new_list = ['carrot' , 'lemon']
      new_list = [fruit for fruit in a if fruit not in b]
      

      或者,使用 for 循环:

      new_list = []
      for fruit in a:
          if fruit not in b:
              new_list.append(fruit)
      

      正如您所见,这些方法非常相似,这就是 Python 还具有列表推导以轻松构建列表的原因。

      【讨论】:

      • 请注意,这会删除b 中所有出现在a 中的元素。所以如果a == [1, 1, 1, 2, 3, 4]b == [1, 3],那么new_list == [2, 4],而不是例如new_list == [1, 1, 2, 4].
      【解决方案5】:

      这对你有用吗?

      a = ["apple", "carrot", "lemon"]
      b = ["pineapple", "apple", "tomato"]
      
      new_list = []
      for v in a:
          if v not in b:
              new_list.append(v)
      
      print new_list
      

      或者,更简洁:

      new_list = filter(lambda v: v not in b, a)
      

      【讨论】:

      • 迄今为止最简洁和pythonic的版本。干得好!
      • 需要注意的是,在更简洁的例子中,new_list不是一个列表。这是一个过滤器迭代器。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-13
      相关资源
      最近更新 更多