python for循环创建一个列表

use*_*925 1 python for-loop list

好的,为什么这个简单的 for 循环无法填充列表?这是我所拥有的:

axx = []
for i in range(1,7):
  axx.append('ax'+str(i))
  print(axx[i])
Run Code Online (Sandbox Code Playgroud)

我收到一个错误:

Traceback (most recent call last):
  File "./bin_data2.py", line 57, in <module>
    print(axx[i])
IndexError: list index out of range
Run Code Online (Sandbox Code Playgroud)

这应该非常简单明了,不是吗?抱歉,来自 Fortran 背景!

stu*_*ent 5

i-1打印时需要。数组从开始0i从 开始追加1。所以,首先append,有元素 at0i值为1

print(axx[i-1])
Run Code Online (Sandbox Code Playgroud)

如果您查看以下结果:

print(list(range(1,7)))
Run Code Online (Sandbox Code Playgroud)

输出:

[1, 2, 3, 4, 5, 6]
Run Code Online (Sandbox Code Playgroud)

或者,您可以将范围更改为range(6)而不是range(1,7)。但是,它将以 值打印0。在这种情况下,你想要axx.append('ax'+str(i+1))