本文介绍了初始化未知长度的numpy数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够动态构建"一个 numpy 数组,但我事先不知道这个数组的大小.

I want to be able to 'build' a numpy array on the fly, I do not know the size of this array in advance.

例如我想做这样的事情:

For example I want to do something like this:

a= np.array()
for x in y:
     a.append(x)

这将导致 a 包含 x 的所有元素,显然这是一个微不足道的答案.我只是好奇这是否可能?

Which would result in a containing all the elements of x, obviously this is a trivial answer. I am just curious whether this is possible?

推荐答案

构建 Python 列表并将其转换为 Numpy 数组.每次追加需要分摊 O(1) 时间 + O(n) 转换为数组,总共 O(n).

Build a Python list and convert that to a Numpy array. That takes amortized O(1) time per append + O(n) for the conversion to array, for a total of O(n).

    a = []
    for x in y:
        a.append(x)
    a = np.array(a)

这篇关于初始化未知长度的numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 15:22
查看更多