Python: initialize multi-dimensional list

后端 未结 8 1379
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-03 05:48

I want to initialize a multidimensional list. Basically, I want a 10x10 grid - a list of 10 lists each containing 10 items.

Each list value should be initialized to

8条回答
  •  执笔经年
    2020-12-03 06:27

    Just thought I'd add an answer because the question asked for the general n-dimensional case and I don't think that was answered yet. You can do this recursively for any number of dimensions with the following example:

    n_dims = [3, 4, 5]
    
    empty_list = 0
    for n in n_dims:
        empty_list = [empty_list] * n
    
    >>>empty_list
    >>>[[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]],
       [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]],
       [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]],
       [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]],
       [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]]
    

提交回复
热议问题