[英]Python create list from specific indexes in a list of lists
我有一個列表列表,我想根據此列表中的特定索引創建多個較小的列表。 如果我有這么大的“矩陣”,我可以創建一個由從這個矩陣收集的整數組成的小列表嗎?
代碼:
matrix = [
[0, 0, 0, 5, 0, 0, 0, 0, 6],
[8, 0, 0, 0, 4, 7, 5, 0, 3],
[0, 5, 0, 0, 0, 3, 0, 0, 0],
[0, 7, 0, 8, 0, 0, 0, 0, 9],
[0, 0, 0, 0, 1, 0, 0, 0, 0],
[9, 0, 0, 0, 0, 4, 0, 2, 0],
[0, 0, 0, 9, 0, 0, 0, 1, 0],
[7, 0, 8, 3, 2, 0, 0, 0, 5],
[3, 0, 0, 0, 0, 8, 0, 0, 0],
]
list1 = ([index 1, row 1], [index 2, row 2])
list2 = ([index 3, row 6], [index 7, row 9])
etc.
我將如何在 Python 中正確執行此操作。 幫我填寫括號中的實際內容。
謝謝!
如果 index1 表示第一個索引,row1 表示第一個行,則在這種情況下 matrix[0][0] = 0。 矩陣[1][0] = 8 矩陣[1][5] = 7
總之,你可以做 matrix[row_index][col_index]
所以
list1 = [ matrix[0,0], matrix[2][2] ]
希望這可以幫助。
list1 = [matrix[1][1], matrix[2][2]]
list2 = [matrix[6][3], matrix[9][7]]
等等...
您基本上在這里有一個列表列表。 您可以通過以下方式調用列表中的項目:
listname[index]
所以....
matrix[0]
會給你[0, 0, 0, 5, 0, 0, 0, 0, 6]
matrix[0][0]
會給你 0.... 即第零個列表的第零個元素。
請記住,任何列表的“第一個”元素實際上是第零個元素。 所以 matrix[1] 會給你列表中的“第二個”東西。
list1 = [matrix[1][1], matrix[2][2]]
list2 = [matrix[6][3], matrix[9][7]]
還有一個注釋可以幫助您提出更好的問題......您給出的示例需要列表,但您的示例是由表示元組的括號分組的項目。 列表用方括號表示。 []
像這樣:
newmatrix = []
for n,i in enumerate(matrix[0]):# assuming the lists are in the same length
templist =[]
for l in matrix:
templist.append(l[n])
print "templist: ",n,"content: ",templist
newmatrix.append(templist)
編輯:剛剛意識到我完全誤讀了這個問題。 不相關的答案,對不起。 不刪除,因為這可能與其他人有關
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.