带有列表生成器的 numpy fromiter

XXX*_*XXL 8 python arrays numpy generator

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.

这是一段非常愚蠢的代码。我想从生成器创建一个列表数组(最后是一个二维数组)...

虽然我到处搜索,但我仍然不知道如何使它工作。

Ana*_*mar 6

您只能用于numpy.fromiter()创建一维数组(不是二维数组),如文档中numpy.fromiter给出-

numpy.fromiter(iterable, dtype, count=-1)

从一个可迭代对象创建一个新的一维数组。

您可以做的一件事是将生成器函数转换为从中给出单个值c,然后从中创建一个一维数组,然后将其整形为(-1,5). 例子 -

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))
Run Code Online (Sandbox Code Playgroud)

演示 -

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]])
Run Code Online (Sandbox Code Playgroud)

  • PS:事实上,这个解决方案(我不是说你的,我说的是我的)在我的情况下并没有提高性能...... (2认同)