gpt4 book ai didi

python - 从python中的列表中删除项目

转载 作者:太空宇宙 更新时间:2023-11-03 12:49:44 25 4
gpt4 key购买 nike

我是 python 的新手,我想知道如何从列表中删除项目。假设我有列表:

a=[(102,12,0),(123,12,0),(124,12,1)]

我想删除末尾有 0 的项目,所以我的列表最终会像这样:

a = [(124,12,1)]

最佳答案

这里:

a = [i for i in a if i[-1] != 0] #list comprehension (1 line) method.

当父列表也是目标列表时,没有列表理解的“正常”方式。

tmp = []
for i in a:
if i[-1] != 0:
tmp.append(i)
a = tmp

在行动中:

>>> a=[(102,12,0),(123,12,0),(124,12,1)]
>>> a = [i for i in a if i[-1] != 0]
>>> a
[(124, 12, 1)]
>>>

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

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