Python: initialize multi-dimensional list

后端 未结 8 1378
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-03 05:48

I want to initialize a multidimensional list. Basically, I want a 10x10 grid - a list of 10 lists each containing 10 items.

Each list value should be initialized to

8条回答
  •  独厮守ぢ
    2020-12-03 06:24

    Yet another method, but using the OP's rejected method.

    import numpy as np
    myList = [[0]*10]*10
    myList = np.array(myList)
    l=myList.tolist()
    myList=l
    

    The output and testing below:

    >>> l
    [[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, 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], [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, 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]]
    >>> l[0][0]=100
    >>> l
    [[100, 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, 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, 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, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
    

    The output is unlike the expected clone of l[0].

    Although this is not time efficient. It takes nearly 7 seconds for a 1000X1000 list, where as list comprehensions took only 0.0052158 seconds for the same.

提交回复
热议问题