Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/329.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 奇怪的for循环语句_Python_For Loop - Fatal编程技术网

Python 奇怪的for循环语句

Python 奇怪的for循环语句,python,for-loop,Python,For Loop,我看到这个循环,我不太明白为什么最后一个打印是2。 为什么不是3 a = [0, 1, 2, 3] for a[-1] in a: print(a[-1]) 输出: for循环使用a[-1]作为目标变量,从输入iterable分配每个值: for <target> in <iterable> 除了最后一次迭代外,另一次迭代将a[2]放入a[3](或a[-2]放入a[-1]),这就是为什么在最后一次迭代发生时,您会再次看到2 看,;它采用一个通用的target

我看到这个循环,我不太明白为什么最后一个打印是2。 为什么不是3

a = [0, 1, 2, 3]

for a[-1] in a:
    print(a[-1])
输出:


for
循环使用
a[-1]
作为目标变量,从输入iterable分配每个值:

for <target> in <iterable>
除了最后一次迭代外,另一次迭代将
a[2]
放入
a[3]
(或
a[-2]
放入
a[-1]
),这就是为什么在最后一次迭代发生时,您会再次看到
2

看,;它采用一个通用的target_列表作为分配目标,就像一个。在作业中,您不仅限于简单的名称,而且您也不在
for
循环中

for <target> in <iterable>
>>> a = [0, 1, 2, 3]
>>> for a[-1] in a:
...     print a
...
[0, 1, 2, 0]  # assigned a[0] == 0 to a[-1] (or a[3])
[0, 1, 2, 1]  # assigned a[1] == 1 to a[-1]
[0, 1, 2, 2]  # assigned a[2] == 2 to a[-1]
[0, 1, 2, 2]  # assigned a[3] == 2 (since the previous iteration) to a[-1]