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 ?
Run Code Online (Sandbox Code Playgroud)
错误说 ValueError: setting an array element with a sequence.
这是一段非常愚蠢的代码。我想从生成器创建一个列表数组(最后是一个二维数组)...
虽然我到处搜索,但我仍然不知道如何使它工作。
我想创建一个在飞行中返回数组的生成器.例如:
import numpy as np
def my_gen():
c = np.ones(5)
j = 0
t = 10
while j < t:
c[0] = j
yield c
j += 1
Run Code Online (Sandbox Code Playgroud)
使用简单的for循环:
for g in my_gen():
print (g)
Run Code Online (Sandbox Code Playgroud)
我得到了我想要的东西.但是list(my_gen()),我得到了一个包含始终相同的列表.
我挖得更深一些,我发现当我yield c.tolist()而不是yield c一切都好的时候......
我只是无法解释自己为何会出现这种奇怪的行为......