【问题标题】:List comprehension applicable for removing matching items from another list?列表理解适用于从另一个列表中删除匹配项?
【发布时间】:2021-10-20 20:37:45
【问题描述】:

我正在尝试找出与另一个列表(测试)中的项目匹配时删除列表项目(水果)的最佳方法。

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
test = ["nana", "erry"]
newList = ["apple", "banana", "cherry", "kiwi", "mango"]

for x in test:
    for y in fruits:
        if x in y:
            newList.remove(y)

print(newList)

newList 的输出符合预期:['apple', 'kiwi', 'mango']

如果我尝试通过列表理解来解决这个问题,项目将被删除,但列表会在 for 循环中打印两次。

fruitsNew = [y for x in test for y in fruits if x not in y]

print(fruitsNew)

fruitsNew 的输出是:['apple', 'cherry', 'kiwi', 'mango', 'apple', 'banana', 'kiwi', 'mango']

在第一次迭代中,匹配“nana”的项目被删除,在第二次迭代中,匹配“erry”的单词被删除。有没有办法在删除匹配项的同时只打印一次列表?或者这个问题的列表理解不适用?

问候

【问题讨论】:

    标签: python list for-loop list-comprehension


    【解决方案1】:

    您可以为此使用any

    fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
    test = ["nana", "erry"]
    newList = ["apple", "banana", "cherry", "kiwi", "mango"]
    
    res = [i for i in fruits if not any(j in i for j in test)]
    
    print(res)
    

    输出

    ['apple', 'kiwi', 'mango']
    

    【讨论】:

      【解决方案2】:

      在这里,您复制了源列表并从副本中删除了元素。那将是低效的。为什么不根据标准建立新的名单呢?这就是列表推导的用途。

      fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
      test = ["nana", "erry"]
      
      newlist = [name for name in fruits if all(t not in name for t in test)]
      
      assert newlist == ['apple', 'kiwi', 'mango']
      

      换句话说,尽量避免具有副作用的列表推导。在这里,从不同的列表中删除元素是一个副作用。如果你真的需要,只需使用 for 循环形式。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-17
        • 2011-02-14
        • 1970-01-01
        • 2014-10-08
        • 1970-01-01
        相关资源
        最近更新 更多