Python multi-dimensional array initialization without a loop

前端 未结 12 1003
梦谈多话
梦谈多话 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 23:00

    I don't believe it's possible.

    You can do something like this:

    >>> a = [[0] * 5] * 5
    

    to create a 5x5 matrix, but it is repeated objects (which you don't want). For example:

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

    You almost certainly need to use some kind of loop as in:

    [[0 for y in range(5)] for x in range(5)]
    

提交回复
热议问题