此for循环如何工作?

时间:2019-10-10 03:31:37

标签: python-3.x

运行此代码时,输​​出将打印为4 46。请说明此循环如何工作?

li=[4,5,6]
for li[1] in li:
    print(li[1])

1 个答案:

答案 0 :(得分:2)

这是将值从li分配到li[1]

如果展开循环,则会得到:

li=[4,5,6]
li[1] = li[0] # li[0] = 4
print(li[1])
>>> 4 # li = [4, 4, 6]
li[1] = li[1] # li[1] = 4
print(li[1])
>>> 4 # li = [4, 4, 6]
li[1] = li[2] # li[2] = 6
print(li[1])
>>> 6 # li = [4, 6, 6]

您也可以将其写为:

li=[4,5,6]
for i in range(3):
  li[1] = li[i]
  print(li[1])

我不建议这样做