Multidimensional array in Python

前端 未结 12 1526
独厮守ぢ
独厮守ぢ 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:20

    To create a standard python array of arrays of arbitrary size:

    a = [[0]*cols for _ in [0]*rows]
    

    It is accessed like this:

    a[0][1] = 5 # set cell at row 0, col 1 to 5
    

    A small python gotcha that's worth mentioning: It is tempting to just type

    a = [[0]*cols]*rows
    

    but that'll copy the same column array to each row, resulting in unwanted behaviour. Namely:

    >>> a[0][0] = 5
    >>> print a[1][0]
    5
    

提交回复
热议问题