Multidimensional array in Python

前端 未结 12 1525
独厮守ぢ
独厮守ぢ 2021-02-04 15:49

I have a little Java problem I want to translate to Python. Therefor I need a multidimensional array. In Java it looks like:

double dArray[][][] = new double[x.l         


        
12条回答
  •  醉梦人生
    2021-02-04 16:15

    Here's a quick way to create a nested 3-dimensional list initialized with zeros:

    # dim1, dim2, dim3 are the dimensions of the array
    a =[[[0 for _ in range(dim1)] for _ in range(dim2)] for _ in range(dim1) ]
    a[0][0][0] = 1
    

    this is a list of lists of lists, a bit more flexible than an array, you can do:

    a[0][0] = [1,2,3,4]
    

    to replace a whole row in the array, or even abuse it like that:

    a[0] = "Ouch"
    print a[0][0] #will print "O", since strings are indexable the same way as lists
    print a[0][0][0] #will raise an error, since "O" isn't indexable
    

    but if you need performance, then I agree that numpy is the way to go.

    Also, beware of:

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

    If you try a[0][0][0]=7 on the object above, you will see what's wrong with that.

提交回复
热议问题