Python:在遍历列表时编辑列表 [英] Python: Editing list while iterating over it
问题描述
Stack上有一些相关的问题,但我想尽可能清楚.我正在使用Python 3
There are some related questions on Stack but I wanted to be as clear as possible. I am using Python 3
如果我有一个列表,N
,并且我使用以下代码:
If I have a list, N
, and I use the following code:
N = [1,2,3,4,6,7,8]
for x in N:
N[x] = N[x] * -1
return N
我得到一个Index out of range error
.我知道您不应该在遍历列表时添加和删除元素,但是我想清楚地定义为什么上面的示例不起作用,对我来说似乎应该没有问题.在第一次迭代中,x
应该计算为1
.因此,如果我想编辑N[1]
,我不明白为什么我无法编辑.
I am getting a Index out of range error
. I understand you shouldn't be adding and deleting elements while iterating over a list, but I wanted a clear definition of why the above example won't work.To me, it seems like there shouldn't be a problem. In the first iteration, x
should evaluate to 1
. So if I want to edit N[1]
, I don't see why I wouldn't be able to.
作为旁注,我知道enumerate()
是执行此操作的正确方法.
As a side note, I know enumerate()
is the proper way to do it.
推荐答案
使用enumerate
例如:
N = [1,2,3,4,6,7,8]
for x, value in enumerate(N):
N[x] = value * -1
print(N)
或列表理解.
例如:
N = [x * -1 for x in N]
这篇关于Python:在遍历列表时编辑列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!