List 以Python方式创建列表列表

List 以Python方式创建列表列表,list,matrix,python,List,Matrix,Python,我正在使用列表列表在python中存储矩阵。我尝试初始化一个2x3零矩阵,如下所示 mat=[[0]*2]*3 但是,当我更改矩阵中一个项目的值时,它会更改每一行中该条目的值,因为mat中每一行的id都是相同的。例如,在分配 mat[0][0]=1 mat是[[1,0],[1,0],[1,0]] 我知道我可以使用循环创建零矩阵,如下所示 mat=[[0]*2] for i in range(1,3): mat.append([0]*2) 但是有谁能给我展示一种更具Python风格的

我正在使用列表列表在python中存储矩阵。我尝试初始化一个2x3零矩阵,如下所示

mat=[[0]*2]*3
但是,当我更改矩阵中一个项目的值时,它会更改每一行中该条目的值,因为
mat
中每一行的id都是相同的。例如,在分配

mat[0][0]=1
mat
[[1,0],[1,0],[1,0]]

我知道我可以使用循环创建零矩阵,如下所示

mat=[[0]*2]
for i in range(1,3):
    mat.append([0]*2)
但是有谁能给我展示一种更具Python风格的方式吗?

试试这个:

>>> cols = 6
>>> rows = 3
>>> a = [[0]*cols for _ in [0]*rows]
>>> a
[[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]
>>> a[0][3] = 2
>>> a
[[0, 0, 0, 2, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]
还讨论了这一点:

这会奏效的

col = 2
row = 3
[[0] * col for row in xrange(row)]
那么:

m, n = 2, 3
>>> A = [[0]*m for _ in range(n)]
>>> A
[[0, 0], [0, 0], [0, 0]]
>>> A[0][0] = 1
[[1, 0], [0, 0], [0, 0]]
又名列表理解;从:

使用:

或者,作为一种功能:

def matrix(rows, cols):
    return [[0]*cols for x in xrange(rows)]
我用


尽管这取决于创建矩阵后对矩阵所做的操作,但您可能会考虑使用NumPy数组。

有什么是itertools不能做的吗?:)


这个比公认的答案快
使用xrange(行)而不是[0]*行没有区别

>>> from itertools import repeat
>>> rows,cols = 3,6
>>> a=[x[:] for x in repeat([0]*cols,rows)]
不使用itertools并以相同速度运行的变体

>>> a=[x[:] for x in [[0]*cols]*rows]
来自ipython:

In [1]: from itertools import repeat

In [2]: rows=cols=10

In [3]: timeit a = [[0]*cols for _ in [0]*rows]
10000 loops, best of 3: 17.8 us per loop

In [4]: timeit a=[x[:] for x in repeat([0]*cols,rows)]
100000 loops, best of 3: 12.7 us per loop

In [5]: rows=cols=100

In [6]: timeit a = [[0]*cols for _ in [0]*rows]
1000 loops, best of 3: 368 us per loop

In [7]: timeit a=[x[:] for x in repeat([0]*cols,rows)]
1000 loops, best of 3: 311 us per loop

如果所涉及的尺寸仅为2和3

mat = [[0, 0], [0, 0], [0, 0]]

很容易就是最好的,还没有被提及。

谢谢,这就是我要找的+1-好东西。我只是在学习Python,所以我非常欣赏看到“Python”代码的片段;您正在创建一个列表,该列表除了其长度之外,没有任何其他用途。使用
xrange(n)
或(不太可能)
itertools。在Python中重复(None,n)
来做一些
n
次。应该有一种——最好只有一种——明显的方法来做这件事我将在某个时候探索NumPy,但对于我目前的问题,一个列表就足够了。
>>> from itertools import repeat,izip
>>> rows=3
>>> cols=6
>>> A=map(list,izip(*[repeat(0,rows*cols)]*cols))
>>> A
[[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]
>>> A[0][3] = 2
>>> A
[[0, 0, 0, 2, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]
>>> from itertools import repeat
>>> rows,cols = 3,6
>>> a=[x[:] for x in repeat([0]*cols,rows)]
>>> a=[x[:] for x in [[0]*cols]*rows]
In [1]: from itertools import repeat

In [2]: rows=cols=10

In [3]: timeit a = [[0]*cols for _ in [0]*rows]
10000 loops, best of 3: 17.8 us per loop

In [4]: timeit a=[x[:] for x in repeat([0]*cols,rows)]
100000 loops, best of 3: 12.7 us per loop

In [5]: rows=cols=100

In [6]: timeit a = [[0]*cols for _ in [0]*rows]
1000 loops, best of 3: 368 us per loop

In [7]: timeit a=[x[:] for x in repeat([0]*cols,rows)]
1000 loops, best of 3: 311 us per loop
mat = [[0, 0], [0, 0], [0, 0]]