[英]numpy array equivalent for += operator
I often do the following: 我经常执行以下操作:
import numpy as np
def my_generator_fun():
yield x # some magically generated x
A = []
for x in my_generator_fun():
A += [x]
A = np.array(A)
Is there a better solution to this which operates on a numpy array from the start and avoids the creation of a standard python list? 从头开始对numpy数组进行操作并避免创建标准python列表,对此是否有更好的解决方案?
Note that the += operator allows to extend an empty and dimensionless array with an arbitrarily dimensioned array whereas np.append and np.concatenate demand for equally dimensioned arrays. 请注意,+ =运算符允许使用任意尺寸的数组扩展空无量纲的数组,而np.append和np.concatenate对相等尺寸的数组的需求。
Use np.fromiter
: 使用
np.fromiter
:
def f(n):
for j in range(n):
yield j
>>> np.fromiter(f(5), dtype=np.intp)
array([0, 1, 2, 3, 4])
If you know beforehand the number of items the iterator is going to return, you can speed things up using the count
keyword argument: 如果您事先知道迭代器将要返回的项目数,则可以使用
count
关键字参数来加快速度:
>>> np.fromiter(f(5), dtype=np.intp, count=5)
array([0, 1, 2, 3, 4])
To get the same array A
, do: 要获得相同的数组
A
,请执行以下操作:
A = numpy.arange(5)
Arrays are not in general meant to be dynamically sized, but you could use numpy.concatenate
. 通常,数组并不是要动态调整大小的,但是您可以使用
numpy.concatenate
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.