简体   繁体   中英

Most efficient way to initialize a matrix in python

Whats the most efficient way to initialize a matrix in Python without using numpy. For example I'd like to create:

matrix = [
           [[0,0],[0,0],[0,0]]
           [[0,0],[0,0],[0,0]]
           [[0,0],[0,0],[0,0]]
         ]

I was creating one using:

dpcols = [[0,0]] * len(matrix[0])
matrix = [dpcols] * len(matrix)

But with this, if i change

matrix[1][1] = [1,1]

Then indexes [0][1], [1][1], and [2][1] all gets changed to [1,1], due to them all being linked together.

I don't think this is as efficient as numpy since it's a double for loop, but it's easy to write:

>>> rows,cols = 2,3
>>> a = [[[0,0] for c in range(cols)] for r in range(rows)]
>>> a
[[[0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0]]]
>>> a[1][1] = [1,1]
>>> a
[[[0, 0], [0, 0], [0, 0]], [[0, 0], [1, 1], [0, 0]]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM