[英]Python: How to traverse a list of lists by columns, as if it was a regular 2D array (matrix)?
I have a list of lists like this: list=[[0,1,2,3],[4,5,6,7],[8,9,10,11],[12,13,14,15]]
. 我有一个这样的列表列表:
list=[[0,1,2,3],[4,5,6,7],[8,9,10,11],[12,13,14,15]]
。
I want to use this list in a function that "slices" my list
into 9
groups of four values each, that are dumped into a dict
of lists
. 我想在函数中使用此列表,该函数将我的
list
“切片”成9
组,每组四个值,这些值转储到lists
的dict
中。 If len(list)=n
, the function should create [sqrt(n)-1]*[sqrt(n)-1]
slices. 如果
len(list)=n
,则该函数应创建[sqrt(n)-1]*[sqrt(n)-1]
切片。 In this case, given len(list)=16
, slices=[4-1]*[4-1]=9
. 在这种情况下,给定
len(list)=16
, slices=[4-1]*[4-1]=9
。
This is the function: 这是功能:
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
I think of my list
as a 2D array - a 4x4
matrix in this case - which must be traversed as if it was a matrix: the row
is fixed and the column
is incremented: 我认为我的
list
是2D数组-在这种情况下是4x4
矩阵-必须像矩阵一样遍历它: row
是固定的, column
是递增的:
Columns ->
Rows v 0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15
Therefore, my slices must be [0,1,4,5]
, [1,2,5,6]
, [2,3,6,7]
, [4,5,8,9]
etc., without wrapping the matrix up. 因此,我的片必须是
[0,1,4,5]
[1,2,5,6]
[2,3,6,7]
[4,5,8,9]
等, 无包装矩阵向上。
The final result should be 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]}
. 最终结果应为
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]}
。
My question: is this the correct way for my for
loops to traverse the list by columns (which means: the row is fixed, the column is incremented)? 我的问题:这是我的
for
循环按列遍历列表的正确方法(这意味着:行是固定的,列是递增的)吗? I cannot judge as if I print my list
I only get a regular list so it confuses me. 我无法判断我是否打印
list
但只能得到常规列表,这会使我感到困惑。 Thanks! 谢谢!
I do not know if I understand what you want. 我不知道我是否了解你想要什么。 If you want to show correct results do this
如果要显示正确的结果,请执行此操作
list = dictionarize1(list) #Calling the function
print(list) #your result is ok
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.