Initialise numpy array of unknown length

前端 未结 5 1139
无人及你
无人及你 2020-12-02 08:38

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:



        
5条回答
  •  暖寄归人
    2020-12-02 09:07

    For posterity, I think this is quicker:

    a = np.array([np.array(list()) for _ in y])
    

    You might even be able to pass in a generator (i.e. [] -> ()), in which case the inner list is never fully stored in memory.


    Responding to comment below:

    >>> import numpy as np
    >>> y = range(10)
    >>> a = np.array([np.array(list) for _ in y])
    >>> a
    array([array(, dtype=object),
           array(, dtype=object),
           array(, dtype=object),
           array(, dtype=object),
           array(, dtype=object),
           array(, dtype=object),
           array(, dtype=object),
           array(, dtype=object),
           array(, dtype=object),
           array(, dtype=object)], dtype=object)
    

提交回复
热议问题