gpt4 book ai didi

python - 使用原始输入删除 python 中列表的元素

转载 作者:行者123 更新时间:2023-12-01 05:17:53 24 4
gpt4 key购买 nike

假设我有一个这样的列表:

[['14632','apples'],
['134','oranges'],
['834','bananas'],
['472','tomatoes']]

当用户在函数中输入“oranges”作为参数时,我尝试删除一个项目(例如,['134', 'oranges'])。这是我到目前为止的代码:

def remove_item(my_list, name):
name = raw_input()
for item in my_list:
if name == item[1]:
my_list.remove(item)

其中 item[0] 是数字,item[1] 是字符串。这段代码不起作用,我错过了一些与删除有关的东西,或者我使用了“==”错误?

最佳答案

通过插入或删除元素来修改正在循环的列表通常是有风险的。在 Python 中,删除当前元素会使 for 循环跳过下一项。 Python 手册建议在这种情况下您迭代列表的副本。

来自 Python 3.1.3 文档 - 复合语句 - 8.3 for 语句:

Note There is a subtlety when the sequence is being modified by the loop (this can only occur for mutable sequences, i.e. lists). An internal counter is used to keep track of which item is used next, and this is incremented on each iteration. When this counter has reached the length of the sequence the loop terminates. This means that if the suite deletes the current (or a previous) item from the sequence, the next item will be skipped (since it gets the index of the current item which has already been treated). Likewise, if the suite inserts an item in the sequence before the current item, the current item will be treated again the next time through the loop. This can lead to nasty bugs that can be avoided by making a temporary copy using a slice of the whole sequence, e.g.,

for x in a[:]:
if x < 0: a.remove(x)

关于python - 使用原始输入删除 python 中列表的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22903364/

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