[英]How do you iterate over this array? I know this is very basic
import numpy as np
a=np.arange(6)
for i in a:
b[i]=a[i] + 1
print(b)
this is the error 这是错误
IndexError: list assignment index out of range
IndexError:列表分配索引超出范围
I want b to read [1 2 3 4 5 6]
我想让b阅读
[1 2 3 4 5 6]
for i in array
returns the values, not the indices. for i in array
返回值,而不是索引。 To iterate over the indices, use range(len(a))
instead of just a
. 要遍历索引,请使用
range(len(a))
而不是仅使用a
。
The corrected code: 更正的代码:
for i in range(len(a)):
b[i] = a[i] + 1
The better solution, if you're just looking for 1 to 6, is to do np.arange(1, 7)
如果只想查找1到6,更好的解决方案是执行
np.arange(1, 7)
Edit: As Paul points out, numpy has a much better solution than I knew. 编辑:正如保罗指出的那样,numpy有比我所知道的更好的解决方案。 All you have to do is
b = a + 1
您要做的就是
b = a + 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.