简体   繁体   中英

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.

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. To achieve that result you'll have to reshape your numpy array using either x = x.reshape((5,2)) or x.shape = 5, 2 . 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

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:

import numpy as np
x = np.arange(10)

for i, j in zip(x[::2], x[1::2]):
     print(i,j)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM