gpt4 book ai didi

python - 如何使用 nditer 迭代每个操作数的第一个维度?

转载 作者:行者123 更新时间:2023-12-01 05:44:03 24 4
gpt4 key购买 nike

给定:

import numpy as np
a = np.arange(6)
b = np.arange(24).reshape(6,4)

我想要这样的东西:

for i in xrange(len(a)):
v1 = a[i]
v2 = b[i,...]

但我不知道如何使用 nditer 来做到这一点?

it = np.nditer((a,b))
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-4-7fe57c985cae> in <module>()
----> 1 it = np.nditer((a,b))

ValueError: operands could not be broadcast together with shapes (6) (6,4)

这适用于单个操作数,但如何处理不同级别的操作数?

a = np.arange(6).reshape(2,3)
for x in np.nditer(a, flags=['external_loop'], order='F'):
... print x,

最佳答案

为什么不直接使用zip

>>> for i in xrange(len(a)):
... print a[i],b[i,...]
...
0 [0 1 2 3]
1 [4 5 6 7]
2 [ 8 9 10 11]
3 [12 13 14 15]
4 [16 17 18 19]
5 [20 21 22 23]
>>> for v1,v2 in zip(a,b):
... print v1,v2
...
0 [0 1 2 3]
1 [4 5 6 7]
2 [ 8 9 10 11]
3 [12 13 14 15]
4 [16 17 18 19]
5 [20 21 22 23]

关于python - 如何使用 nditer 迭代每个操作数的第一个维度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16717479/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com