簡體   English   中英

以pythonic方式創建列表列表

[英]Creating lists of lists in a pythonic way

我正在使用列表列表來存儲python中的矩陣。 我嘗試按如下方式初始化2x3 Zero矩陣。

mat=[[0]*2]*3

但是,當我更改矩陣中某個項的值時,它會更改行中該條目的值,因為mat行的id是相同的。 例如,在分配之后

mat[0][0]=1

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

我知道我可以使用循環創建Zero矩陣,如下所示,

mat=[[0]*2]
for i in range(1,3):
    mat.append([0]*2)

但有人能告訴我更多的pythonic方式嗎?

使用列表理解

>>> mat = [[0]*2 for x in xrange(3)]
>>> mat[0][0] = 1
>>> mat
[[1, 0], [0, 0], [0, 0]]

或者,作為一個功能:

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

嘗試這個:

>>> 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]]

這個也在這個答案中討論:

>>> lst_2d = [[0] * 3 for i in xrange(3)]
>>> lst_2d
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> lst_2d[0][0] = 5
>>> lst_2d
[[5, 0, 0], [0, 0, 0], [0, 0, 0]]

這個比接受的答案快!
使用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

我用

mat = [[0 for col in range(3)] for row in range(2)]

雖然取決於您在創建矩陣后對矩陣所做的操作,但您可以查看使用NumPy數組。

這會奏效

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

如果涉及的尺寸實際上只有2和3,

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

是最好的,尚未提及。

關於什么:

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]]

Aka List理解; 來自文檔

List comprehensions provide a concise way to create lists 
without resorting to use of     
map(), filter() and/or lambda. 
The resulting list definition tends often to be clearer    
than lists built using those constructs.

另請參閱此問題以推廣到n級嵌套列表/ n維矩陣。

有沒有什么itertools不能做? :)

>>> 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]]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM