簡體   English   中英

Python-讀取矩陣中的第n行

[英]Python - Read nth line in a matrix

讀取矩陣的第n個字母最簡單的方法是什么?

我以為可以通過簡單的for循環來實現,但到目前為止我還沒有運氣。 到目前為止,我能做的最好的事情是使用一個不完全優雅的計數:

matrix = [[1, 3, 5, 2, 6, 2, 4, 1], [2, 6, 1, 6, 2, 5, 7], [1, 6, 2, 6, 8, 2, 6]]

count = 0
for n in matrix:
     print matrix[count][nth]
     count += 1

例如:讀取每行的第0個數字:1、2、1。讀取每行的第4個數字:6、2、8。

如果您需要大量執行此操作,則可以使用zip(*matrix)轉置zip(*matrix)

>>> matrix = [[1, 3, 5, 2, 6, 2, 4, 1], [2, 6, 1, 6, 2, 5, 7], [1, 6, 2, 6, 8, 2, 6]]
>>> matrix_t = zip(*matrix)
>>> matrix_t
[(1, 2, 1), (3, 6, 6), (5, 1, 2), (2, 6, 6), (6, 2, 8), (2, 5, 2), (4, 7, 6)]
>>> matrix_t[0]
(1, 2, 1)
>>> matrix_t[3]
(2, 6, 6)

這將處理不同長度的行(如您的示例),並支持Python對負索引的特殊解釋(相對於序列末尾)(通過將它們更改為len(s) + n ):

NULL = type('NULL', (object,), {'__repr__': lambda self: '<NULL>'})()

def nth_elems(n):
    abs_n = abs(n)
    return [row[n] if abs_n < len(row) else NULL for row in matrix]

matrix = [[1, 3, 5, 2, 6, 2, 4, 1], [2, 6, 1, 6, 2, 5, 7], [1, 6, 2, 6, 8, 2, 6]]

print nth_elems(0)   # [1, 2, 1]
print nth_elems(6)   # [4, 7, 6]
print nth_elems(7)   # [1, <NULL>, <NULL>]
print nth_elems(-1)  # [1, 7, 6]
In [1]: matrix = [[1, 3, 5, 2, 6, 2, 4, 1], [2, 6, 1, 6, 2, 5, 7], [1, 6, 2, 6, 8, 2, 6]]

In [2]: nth=0

In [3]: [row[nth] for row in matrix]
Out[3]: [1, 2, 1]

In [4]: nth=4

In [5]: [row[nth] for row in matrix]
Out[5]: [6, 2, 8]

也許是這樣嗎?

column = [row[0] for row in matrix]

(對於第0個元素)

這是使用列表理解的解決方案:

[x[0] for x in matrix]

基本上等於:

for x in matrix:
    print x[0]

您還可以使其具有以下功能:

def getColumn(lst, col):
    return [i[col] for i in lst]

演示:

>>> matrix = [[1, 3, 5, 2, 6, 2, 4, 1], [2, 6, 1, 6, 2, 5, 7], [1, 6, 2, 6, 8, 2, 6]]
>>> def getColumn(lst, col):
    return [i[col] for i in lst]

>>> getColumn(matrix, 0)
[1, 2, 1]
>>> getColumn(matrix, 5)
[2, 5, 2]

希望這可以幫助!

列表理解在這里可以很好地工作:

>>> matrix = [[1, 3, 5, 2, 6, 2, 4, 1], [2, 6, 1, 6, 2, 5, 7], [1, 6, 2, 6, 8, 2, 6]]
>>> # Get all the 0th indexes
>>> a = [item[0] for item in matrix]
>>> a
[1, 2, 1]
>>> # Get all the 4th indexes
>>> b = [item[4] for item in matrix]
>>> b
[6, 2, 8]
>>>

您的for循環可能未達到您的期望。 n不是整數。 它是當前行。 我認為您想做的是:

for row in matrix:
    print row[0], row[4]

打印,

1 6
2 2
1 8

同樣,嚴格來說,矩陣是列表的列表。 真正擁有一個矩陣,您可能需要使用numpy。

Python中的列表不能像這樣使用。 如果數據足夠大,則使用列表推導可能會導致內存和CPU問題。 如果這是一個問題,請考慮使用numpy

使用郵編:

>>> matrix = [[1, 3, 5, 2, 6, 2, 4, 1], [2, 6, 1, 6, 2, 5, 7], [1, 6, 2, 6, 8, 2, 6]]
>>> zip(*matrix)[0]
(1, 2, 1)
>>> zip(*matrix)[4]
(6, 2, 8)

暫無
暫無

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

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