Python multi-dimensional array initialization without a loop

前端 未结 12 1023
梦谈多话
梦谈多话 2020-12-13 22:26

Is there a way in Python to initialize a multi-dimensional array / list without using a loop?

12条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-13 22:53

    The following does not use any special library, nor eval:

    arr = [[0]*5 for x in range(6)]
    

    and it doesn't create duplicated references:

    >>> arr[1][1] = 2
    >>> arr
    [[0, 0, 0, 0, 0],
     [0, 2, 0, 0, 0],
     [0, 0, 0, 0, 0],
     [0, 0, 0, 0, 0],
     [0, 0, 0, 0, 0],
     [0, 0, 0, 0, 0]]
    

提交回复
热议问题