列表理解适用于从另一个列表中删除匹配项吗?
List comprehension applicable for removing matching items from another list?
我想找出当列表项(水果)与另一个列表(测试)中的项匹配时删除列表项(水果)的最佳方法。
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”匹配的词。有没有办法在删除匹配项时只打印一次列表?或者这个问题的列表理解不适用?
问候
您可以为此使用 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']
您在这里复制了源列表并从副本中删除了元素。那将是低效的。为什么不直接根据标准建立新列表呢?这就是列表理解的目的。
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 循环形式。
我想找出当列表项(水果)与另一个列表(测试)中的项匹配时删除列表项(水果)的最佳方法。
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”匹配的词。有没有办法在删除匹配项时只打印一次列表?或者这个问题的列表理解不适用?
问候
您可以为此使用 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']
您在这里复制了源列表并从副本中删除了元素。那将是低效的。为什么不直接根据标准建立新列表呢?这就是列表理解的目的。
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 循环形式。