处理一个Numpy数组的拐角情况以进行迭代

时间:2019-04-01 07:54:21

标签: python arrays numpy iteration

我有一个形状相同(但不一定相同的dtype)的Numpy数组的列表,我想同时遍历所有数组的元素。例如,如果数组为:

>>> a = np.array([[1,2,3], [4,5,6]])
>>> b = np.array([['one','two','three'],['four','five','six']])

我希望在[a, b]上进行迭代以产生

[(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four'), (5, 'five'), (6, 'six')]

我发现numpy.nditer几乎可以满足我的需求。这有效:

>>> for x, y in np.nditer([a, b]):
...     print('{} {}'.format(x, y))
1 one
2 two
3 three
4 four
5 five
6 six

请注意,迭代器产生标量的元组:

>>> next(np.nditer([a, b]))
(array(1), array('one', dtype='<U5'))

但是,在包含一个数组的列表的特殊情况下,np.nditer直接生成数组元素:

>>> next(np.nditer([a]))
array(1)

我需要它来生成具有一个元素的元组,因为我要在循环内的函数参数中解压缩迭代值。

当遍历一个数组的列表时,如何说服np.nditer生成一个元素元组?

2 个答案:

答案 0 :(得分:1)

一种解决方法是np.atleast_1D

a = sum(np.ogrid[2:4, 3:5])
b = 2*a
for z in map(np.atleast_1d, np.nditer([a, b])):
    print(np.arange(*z))

#[5 6 7 8 9]
#[ 6  7  8  9 10 11]
#[ 6  7  8  9 10 11]
#[ 7  8  9 10 11 12 13]

for z in map(np.atleast_1d, np.nditer([a])):
    print(np.arange(*z))

#[0 1 2 3 4]
#[0 1 2 3 4 5]
#[0 1 2 3 4 5]
#[0 1 2 3 4 5 6]

请注意,这会将0D数组解压缩,nditer返回正确的标量。此外,它产生数组,而不是元组,但是只要您将它们扩展为一个函数就没关系。

答案 1 :(得分:0)

这与- Root CA Certificate - AddTrustExternalCARoot.crt - Intermediate CA Certificate - USERTrustRSAAddTrustCA.crt - Intermediate CA Certificate - SectigoRSADomainValidationSecureServerCA.crt - Your PositiveSSL Certificate - www_guerrilla_app.crt 的行为背道而驰。

也许您总是可以提供None数组,以便您总是得到一个元组?但是,您必须在函数中处理None。