[英]How to iterate over a numpy array, getting two values per loop?
I envision something like我设想类似的东西
import numpy as np
x = np.arange(10)
for i, j in x:
print(i,j)
and get something like得到类似的东西
0 1
2 3
4 5
6 7
8 9
But I get this traceback:但我得到了这个追溯:
Traceback (most recent call last):
File "/home/andreas/.local/share/JetBrains/Toolbox/apps/PyCharm-P/ch-0/223.8214.51/plugins/python/helpers/pydev/pydevconsole.py", line 364, in runcode
coro = func()
File "<input>", line 1, in <module>
TypeError: cannot unpack non-iterable numpy.int64 object
I also tried to use np.nditer(x)
and itertools
with zip(x[::2], x[1::2])
, but that does not work either, with different error messages.我还尝试将
np.nditer(x)
和itertools
与zip(x[::2], x[1::2])
一起使用,但这也不起作用,并出现不同的错误消息。
This should be super simple, but I can't find solutions online.这应该超级简单,但我无法在网上找到解决方案。
You were trying to put 0
into i
and j
which is not possible.您试图将
0
放入i
和j
,这是不可能的。 To achieve that result you'll have to reshape your numpy array using either x = x.reshape((5,2))
or x.shape = 5, 2
.要实现该结果,您必须使用
x = x.reshape((5,2))
或x.shape = 5, 2
重塑 numpy 数组。 Then you can unpack it like that.然后你可以像这样解压它。
To visualize, this is what your current code is doing:为了形象化,这就是您当前的代码正在做的事情:
i, j = 0
...
i, j = 1
...
And this is what will happen if you reshape it:如果你重塑它,这就是会发生的事情:
i, j = [0, 1]
...
i, j = [2, 3]
...
Edit:编辑:
import numpy as np
N = 10
x = np.arange(N).reshape((N/2, 2))
for i, j in x:
print(i,j)
Is it what you want?这是你想要的吗?
for x in range(0,10,2):
print(x, x+1)
or your values are maintained in the numpy array x, then或者您的值保存在 numpy 数组 x 中,然后
for i in range(0, len(x), 2):
print(x[i],x[i+1])
Trying to be faithful to the original attempt.试图忠实于最初的尝试。
zip
ping tuples of pairs of even and odds: zip
ping 偶数和奇数对的元组:
import numpy as np
x = np.arange(10)
for i, j in zip(x[::2], x[1::2]):
print(i,j)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.