gpt4 book ai didi

python - 从 Python 中的列表中删除列表

转载 作者:IT老高 更新时间:2023-10-28 20:30:44 24 4
gpt4 key购买 nike

Possible Duplicate:
Get difference from two lists in Python

执行此操作的简化方法是什么?我一直在自己尝试,我无法弄清楚。列表 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 还具有列表推导以轻松构建列表的原因。

关于python - 从 Python 中的列表中删除列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11434599/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com