How to create a numpy array of lists?

前端 未结 6 2093
攒了一身酷
攒了一身酷 2020-12-01 12:02

I want to create a numpy array in which each element must be a list, so later I can append new elements to each.

I have looked on google and here on stack overflow a

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-01 12:24

    If you really need a 1-d array of lists you will have to wrap your lists in your own class as numpy will always try to convert your lists to arrays inside of an array (which is more efficient but obviously requires constant size-elements), for example through

    class mylist:
    
        def __init__(self, l):
            self.l=l
    
        def __repr__(self): 
            return repr(self.l)
    
        def append(self, x):
            self.l.append(x)
    

    and then you can change any element without changing the dimension of others

    >>> x = mylist([1,2,3])
    >>> y = mylist([1,2,3])
    >>> import numpy as np
    >>> data = np.array([x,y])
    >>> data
    array([[1,2,3], [1,2,3]], dtype=object)
    >>> data[0].append(2)
    >>> data
    array([[1,2,3,2], [1,2,3]], dtype=object)
    

    Update

    As suggested by ali_m there is actually a way to force numpy to simply create a 1-d array for references and then feed them with actual lists

    >>> data = np.empty(2, dtype=np.object)
    >>> data[:] = [1, 2, 3], [1, 2, 3]
    >>> data
    array([[1, 2, 3], [1, 2, 3]], dtype=object)
    >>> data[0].append(4)
    >>> data
    array([[1, 2, 3, 4], [1, 2, 3]], dtype=object)
    

提交回复
热议问题