我发现这个问题,一边谷歌搜索,但无法理解它是怎么回事?
a = [0, 1, 2, 3]
for a[-1] in a:
print(a[-1])
结果:
0 1 2 2
现在,如果我再打印一次:
a
[0, 1, 2, 2]
另一个类似的例子:
让a为原始列表,即[0,1,2,3]
现在,让我们运行另一个for循环,但是像这样:
for a[0] in a:
print(a[0])
这次的结果是:
0 1 2 3
但又打印了一个:
[3,1,2,3]
所以,我有两个问题:
1)在两种情况下如何更新原始列表?
2)第一种情况下结果的解释是什么,即环路的负指数是什么?
答案 0 :(得分:3)
注意:a[-1]
是指列表的最后一个元素。
在每次循环迭代中通过
分配给a[index]
for a[index] in a:
a[index]
将在循环中分配值a[0]
,a[1]
,...,a[-1]
,最终分配给
a[index] = a[-1]
通常你不要乱用你正在迭代的列表:
for item in a:
# do something with item
答案 1 :(得分:1)
这是因为在Python中,这个:
a = [0, 1, 2, 3]
for i in a:
... statements ...
可以理解为:
a = [0, 1, 2, 3]
it = iter(a)
i = next(it)
... statements ...
i = next(it)
... statements ...
i = next(it)
... statements ...
i = next(it)
... statements ...
现在,如果您将i
替换为a[index]
,那么您最终会将a[index]
替换为您迭代的最后一个元素,这是列表中的最后一个元素。
答案 2 :(得分:1)
如果您将其重构为while循环,这会很直观
a = [0, 1, 2, 3]
for a[-1] in a:
print(a[-1])
成为
a = [0, 1, 2, 3]
while i < len(a):
e = a[i]
a[-1] = e # the last element is constantly being overwritten
print(a[-1]) # same as a[i]
因此,随着时间的推移值如下
[0, 1, 2, 3] # original
[0, 1, 2, 0] # prints 0
|--------^
[0, 1, 2, 1] # prints 1
|-----^
[0, 1, 2, 2] # prints 2
|--^
[0, 1, 2, 2] # prints 2
|^
在第二种情况下类似
for a[0] in a:
print(a[0])
成为
a = [0, 1, 2, 3]
while i < len(a):
e = a[i]
a[0] = e # the first element is constantly being overwritten
print(a[0]) # same as a[i]
a的值为
[0, 1, 2, 3] # original
[0, 1, 2, 3] # prints 0
^|
[1, 1, 2, 3] # prints 1
^--|
[2, 1, 2, 2] # prints 2
^-----|
[3, 1, 2, 3] # prints 3
^--------|