用循环附加到列表 [英] Appending to list with loop

查看:75
本文介绍了用循环附加到列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对这条Python感到困惑.从我的理解来看,它只应该循环一次,因为列表中只有一个元素,但是它似乎是连续循环的,我不知道为什么.我知道如何让它工作以完成我想要的工作,但是我只是困惑为什么这从一开始就行不通.谢谢

i'm confused with this piece of python. From my understanding it should only do the loop once as there is only one element in the list however it seems to continuously loop and I have no idea why. I know how to get it working to do what I want but i'm just confused as to why this didn't work to begin with. Thanks

y=["hello"]
for n in y:
    y.append("e")

推荐答案

每次循环迭代时,您都将新元素添加到y中.在第一次迭代中,它将看到'hello',然后附加一个'e'.在第二次迭代中,它看到'e'并附加了另一个,然后在第三次迭代中,看到了一个,依此类推.如果您尝试删除而不是将元素添加到要迭代的列表中,则会发生类似的问题.如果要避免这种情况,请遍历副本:

You are adding new elements to y with each iteration of the loop. On the first iteration, it will see 'hello' and then append an 'e'. On the second iteration, it sees that 'e' and appends another, then on the third it sees that one, and so on. Similar problems occur if you try to delete, rather than append, elements to a list you're iterating over. If you want to avoid this, iterate over a copy:

>>> y = ["hello"]
>>> for n in y[:]:
...     y.append("e")
...
>>> y
['hello', 'e']

这篇关于用循环附加到列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆