[英]Python: How to traverse a list of lists by columns, as if it was a regular 2D array (matrix)?
我有一個這樣的列表列表: list=[[0,1,2,3],[4,5,6,7],[8,9,10,11],[12,13,14,15]]
。
我想在函數中使用此列表,該函數將我的list
“切片”成9
組,每組四個值,這些值轉儲到lists
的dict
中。 如果len(list)=n
,則該函數應創建[sqrt(n)-1]*[sqrt(n)-1]
切片。 在這種情況下,給定len(list)=16
, slices=[4-1]*[4-1]=9
。
這是功能:
def dictionarize1(array):
dict1 = {}
count = 0
for x in range(len(array[0]) - 1) :
for y in range(len(array[0]) - 1):
dict1[count] = [array[x][y], array[x][y+1], array[x+1][y], array[x + 1][y+1]]
count = count + 1
return dict1
dictionarize1(list) #Calling the function
我認為我的list
是2D數組-在這種情況下是4x4
矩陣-必須像矩陣一樣遍歷它: row
是固定的, column
是遞增的:
Columns ->
Rows v 0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15
因此,我的片必須是[0,1,4,5]
[1,2,5,6]
[2,3,6,7]
[4,5,8,9]
等, 無包裝矩陣向上。
最終結果應為dict={'0':[0,1,4,5],'1':[1,2,5,6],'2':[2,3,6,7],'3':[4,5,8,9],'4':[5,6,9,10],'5':[6,7,10,11],'6':[8,9,12,13],'7':[9,10,13,14],'8':[10,11,14,15]}
。
我的問題:這是我的for
循環按列遍歷列表的正確方法(這意味着:行是固定的,列是遞增的)嗎? 我無法判斷我是否打印list
但只能得到常規列表,這會使我感到困惑。 謝謝!
我不知道我是否了解你想要什么。 如果要顯示正確的結果,請執行此操作
list = dictionarize1(list) #Calling the function
print(list) #your result is ok
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.