Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中协调np.fromiter和多维数组_Python_Arrays_Numpy_Multidimensional Array_Lazy Evaluation - Fatal编程技术网

在Python中协调np.fromiter和多维数组

在Python中协调np.fromiter和多维数组,python,arrays,numpy,multidimensional-array,lazy-evaluation,Python,Arrays,Numpy,Multidimensional Array,Lazy Evaluation,我喜欢使用np.fromiterfromnumpy,因为这是一种构建np.array对象的资源惰性方法。然而,它似乎不支持多维数组,这也是非常有用的 import numpy as np def fun(i): """ A function returning 4 values of the same type. """ return tuple(4*i + j for j in range(4)) # Trying to create a 2-dimensional

我喜欢使用
np.fromiter
from
numpy
,因为这是一种构建
np.array
对象的资源惰性方法。然而,它似乎不支持多维数组,这也是非常有用的

import numpy as np

def fun(i):
    """ A function returning 4 values of the same type.
    """
    return tuple(4*i + j for j in range(4))

# Trying to create a 2-dimensional array from it:
a = np.fromiter((fun(i) for i in range(5)), '4i', 5) # fails

# This function only seems to work for 1D array, trying then:
a = np.fromiter((fun(i) for i in range(5)),
        [('', 'i'), ('', 'i'), ('', 'i'), ('', 'i')], 5) # painful

# .. `a` now looks like a 2D array but it is not:
a.transpose() # doesn't work as expected
a[0, 1] # too many indices (of course)
a[:, 1] # don't even think about it
如何使
a
成为多维数组,同时保持基于生成器的惰性构造?

本身只支持构造1D数组,因此,它需要一个可生成单个值的iterable,而不是元组/列表/序列等。解决此限制的一种方法是使用惰性方式将生成器表达式的输出“解包”为单个1D值序列:

import numpy as np
from itertools import chain

def fun(i):
    return tuple(4*i + j for j in range(4))

a = np.fromiter(chain.from_iterable(fun(i) for i in range(5)), 'i', 5 * 4)
a.shape = 5, 4

print(repr(a))
# array([[ 0,  1,  2,  3],
#        [ 4,  5,  6,  7],
#        [ 8,  9, 10, 11],
#        [12, 13, 14, 15],
#        [16, 17, 18, 19]], dtype=int32)