我正在尝试编写一个遍历矩阵的函数。满足条件时,它会记住位置。
我从一个空列表开始:
locations = []
当函数遍历行时,我使用:
附加坐标locations.append(x)
locations.append(y)
在功能结束时,列表如下所示:
locations = [xyxyxyxyxyxy]
我的问题是:
使用追加,是否可以制作列表,使其遵循此格式:
locations = [[[xy][xy][xy]][[xy][xy][xy]]]
第一个括号是否表示矩阵中某一行的位置,而每个位置都在行内的自己的括号中?
在此示例中,第一个括号是第一行,总共有3个坐标,然后是第二个括号,用另外3个坐标表示第二行。
答案 0 :(得分:5)
而不是
locations.append(x)
你可以做到
locations.append([x])
这将附加一个包含x的列表。
所以要做你想要的东西建立你想要添加的列表,然后附加该列表(而不是仅仅附加值)。类似的东西:
##Some loop to go through rows
row = []
##Some loop structure
row.append([x,y])
locations.append(row)
答案 1 :(得分:1)
试试这个:
locations = [[]]
row = locations[0]
row.append([x, y])
答案 2 :(得分:1)
尝试类似:
def f(n_rows, n_cols):
locations = [] # Empty list
for row in range(n_rows):
locations.append([]) # 'Create' new row
for col in range(n_cols):
locations[row].append([x, y])
return locations
<强>测试强>
n_rows = 3
n_cols = 3
locations = f(n_rows, n_cols)
for e in locations:
print
print e
>>>
[[0, 0], [0, 1], [0, 2]]
[[1, 0], [1, 1], [1, 2]]
[[2, 0], [2, 1], [2, 2]]
答案 3 :(得分:1)
简单的例子
locations = []
for x in range(3):
row = []
for y in range(3):
row.append([x,y])
locations.append(row)
print locations
结果:
[[[0, 0], [0, 1], [0, 2]], [[1, 0], [1, 1], [1, 2]], [[2, 0], [2, 1], [2, 2]]]