gpt4 book ai didi

python - 遍历列表python的列表

转载 作者:行者123 更新时间:2023-11-28 20:04:59 25 4
gpt4 key购买 nike

我的代码遇到一个问题,一旦从列表列表中删除列表,循环就会停止运行。

data=[["why","why","hello"],["why","why","bell"],["why","hi","sllo"],["why","cry","hello"]]

for word_set in data:
if word_set[-1]!="hello":
data.remove(word_set)
print(data)

我想要的输出是

[['why', 'why', 'hello'], ['why', 'cry', 'hello']]

但是输出是

[['why', 'why', 'hello'], ['why', 'hi', 'sllo'], ['why', 'cry', 'hello']]

如何让循环一直持续到列表末尾?

最佳答案

这是因为,当您删除第二个项目(其索引为 1)时,它之后的项目会向前移动。在下一次迭代中,索引为 2。它应该指向 ["why","hi","solo"]。但由于项目向前移动,它指向 ["why","cry","hello"]。这就是您得到错误结果的原因。

不建议在遍历列表时删除列表项。

您可以创建一个新列表(在第一个答案中提到)或使用 filter 函数。

def filter_func(item):
if item[-1] != "hello":
return False
return True

new_list = filter(filter_func, old_list)

关于python - 遍历列表python的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33865029/

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