python - 如何从生成器构建 numpy 数组?

如何从生成器对象构建一个 numpy 数组?

让我来说明问题:

>>> import numpy
>>> def gimme():
...   for x in xrange(10):
...     yield x
...
>>> gimme()
<generator object at 0x28a1758>
>>> list(gimme())
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> numpy.array(xrange(10))
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> numpy.array(gimme())
array(<generator object at 0x28a1758>, dtype=object)
>>> numpy.array(list(gimme()))
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

在本例中,gimme() 是我想将其输出转换为数组的生成器。但是,数组构造函数不会遍历生成器,它只是存储生成器本身。我想要的行为是来自 numpy.array(list(gimme())),但我不想支付将中间列表和最终数组放在内存中的内存开销同时。有没有更节省空间的方法?

最佳答案

这个stackoverflow结果后面google了一下,发现有一个numpy.fromiter(data, dtype, count) .默认的 count=-1 从可迭代对象中获取所有元素。它需要明确设置 dtype。就我而言,这很有效:

numpy.fromiter(something.generate(from_this_input), float)

https://stackoverflow.com/questions/367565/

相关文章:

python - 我如何告诉 matplotlib 我完成了一个情节?

linux - 如何在 Linux 上的某个时间运行脚本?

linux - WGET 是否超时?

linux - tar:添加当前目录中的所有文件和目录,包括 .svn 等

python - 删除字符串的第一个字符

python - 在python中调用带有参数列表的函数

python - 如何中止 Python 脚本的执行?

linux - Bash 中的多线程

python - 如何使用 Python 登录网页并检索 cookie 以供以后使用?

python - 更新不同深度的嵌套字典的值