numpy fromiter与列表生成器 [英] numpy fromiter with generator of list
问题描述
import numpy as np
def gen_c():
c = np.ones(5, dtype=int)
j = 0
t = 10
while j < t:
c[0] = j
yield c.tolist()
j += 1
# What I did:
# res = np.array(list(gen_c())) <-- useless allocation of memory
# this line is what I'd like to do and it's killing me
res = np.fromiter(gen_c(), dtype=int) # dtype=list ?
错误提示ValueError: setting an array element with a sequence.
这是一段非常愚蠢的代码.我想从生成器创建一个列表数组(最终是2D数组)...
This is a very stupid piece of code. I'd like to create an array of list(finally a 2D array) from a generator...
尽管我到处搜索,但仍然无法弄清楚它如何工作.
Although I searched everywhere, I still cannot figure out how to make it work.
推荐答案
您只能使用 numpy.fromiter()
来创建一维数组(而不是二维数组),如
You can only use numpy.fromiter()
to create 1-dimensional arrays (not 2-D arrays) as given in the documentation of numpy.fromiter
-
numpy.fromiter(iterable,dtype,count = -1)
从可迭代对象创建新的一维数组.
Create a new 1-dimensional array from an iterable object.
您可以做的一件事是转换生成器函数以从c
中给出单个值,然后从中创建一个一维数组,然后将其重塑为(-1,5)
.示例-
One thing you can do is convert your generator function to give out single values from c
and then create a 1D array from it and then reshape it to (-1,5)
. Example -
import numpy as np
def gen_c():
c = np.ones(5, dtype=int)
j = 0
t = 10
while j < t:
c[0] = j
for i in c:
yield i
j += 1
np.fromiter(gen_c(),dtype=int).reshape((-1,5))
演示-
In [5]: %paste
import numpy as np
def gen_c():
c = np.ones(5, dtype=int)
j = 0
t = 10
while j < t:
c[0] = j
for i in c:
yield i
j += 1
np.fromiter(gen_c(),dtype=int).reshape((-1,5))
## -- End pasted text --
Out[5]:
array([[0, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[2, 1, 1, 1, 1],
[3, 1, 1, 1, 1],
[4, 1, 1, 1, 1],
[5, 1, 1, 1, 1],
[6, 1, 1, 1, 1],
[7, 1, 1, 1, 1],
[8, 1, 1, 1, 1],
[9, 1, 1, 1, 1]])
这篇关于numpy fromiter与列表生成器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!