How to create a numpy array of lists?

前端 未结 6 2119
攒了一身酷
攒了一身酷 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:19

    Lists aren't very numpy anyway, so maybe a tuple of lists is good enough for you. You can get that easily and rather efficiently with an iterator expression:

    fiveLists = tuple([] for _ in range(5))
    

    You can leave out the tuple if you only need it once (gives you the raw iterator).

    You can use this to create a numpy array if you really want to:

    arrayOfLists = np.fromiter(([] for _ in range(5)), object)
    

    Edit: as of July 2020, you get "ValueError: cannot create object arrays from iterator"

提交回复
热议问题