Python multi-dimensional array initialization without a loop

前端 未结 12 997
梦谈多话
梦谈多话 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]]
    
    0 讨论(0)
  • 2020-12-13 22:57

    It depends on what you what to initialize the array to, but sure. You can use a list comprehension to create a 5×3 array, for instance:

    >>> [[0 for x in range(3)] for y in range(5)]
    [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
    
    >>> [[3*y+x for x in range(3)] for y in range(5)]
    [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], [12, 13, 14]]
    

    Yes, I suppose this still has loops—but it's all done in one line, which I presume is the intended meaning of your question?

    0 讨论(0)
  • 2020-12-13 22:58

    Depending on your real needs, the de facto "standard" package Numpy might provide you with exactly what you need.

    You can for instance create a multi-dimensional array with

    numpy.empty((10, 4, 100))  # 3D array
    

    (initialized with arbitrary values) or create the same arrays with zeros everywhere with

    numpy.zeros((10, 4, 100))
    

    Numpy is very fast, for array operations.

    0 讨论(0)
  • 2020-12-13 23:00

    Sure there is a way

    arr = eval(`[[0]*5]*10`)
    

    or

    arr = eval(("[[0]*5]+"*10)[:-1])
    

    but it's horrible and wasteful, so everyone uses loops (usually list comprehensions) or numpy

    0 讨论(0)
  • 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)]
    
    0 讨论(0)
  • 2020-12-13 23:01

    If you're doing numerical work using Numpy, something like

    x = numpy.zeros ((m,n))
    x = numpy.ones ((m,n))
    
    0 讨论(0)
提交回复
热议问题