python - 带有列表生成器的 numpy fromiter

标签 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 ?

错误说 ValueError: setting an array element with a sequence.

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

虽然我到处搜索,但我仍然无法弄清楚如何让它工作。

最佳答案

您只能使用 numpy.fromiter()创建在 documentation of numpy.fromiter 中给出的一维数组(不是二维数组) -

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

Create a new 1-dimensional array from an iterable object.

您可以做的一件事是转换您的生成器函数以从 c 中给出单个值,然后从中创建一个一维数组,然后将其 reshape 为 (-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))

演示 -

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]])

关于python - 带有列表生成器的 numpy fromiter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32997108/

相关文章:

python - 在图书馆中寻找正确的方法

python - 如何修复 Pygame 游戏中不需要的角色加速?

python - 我的 R 平方分数为负,但使用 k 倍交叉验证的准确度分数约为 92%

javascript - 如何使用文字创建包含数组的对象

php - 以特定顺序显示数据库中的数据 : php or mysql?

python - randomkit.h 发生了什么或如何迁移到最新的 numpy.random c/cython api

python - 如何从Notepad++卸载Python缩进插件?

python - Django 导入错误 - 没有名为 django.conf.urls.defaults 的模块

c# - 如何在 C# 中调整多维 (2D) 数组的大小?

python - 数组除法——从 MATLAB 到 Python 的翻译