这个问题已经在这里有了答案:




已关闭8年。






简化的方法是什么?我一直在自己尝试,但无法解决。
列表a和列表b,新列表应具有仅在列表a中的项目。所以:

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

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

最佳答案

您可以使用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也具有列表理解功能以轻松构造列表的原因。

10-01 17:16
查看更多