【发布时间】:2021-07-18 02:59:53
【问题描述】:
在 Python 中,我试图创建一个 1x2 数组列表的列表。我将如何使用 for 循环构建以下列表?
[ [ [0 0] , [0 1] , [0 2] , [0 3] ],
[ [1 0] , [1 1] , [1 2] , [1 3] ],
[ [2 0] , [2 1] , [2 2] , [2 3] ],
[ [3 0] , [3 1] , [3 2] , [3 3] ] ]
这似乎是一个非常微不足道的问题,所以我尝试了许多嵌套循环方法来尝试创建它,但没有运气。以下是我最接近的尝试。
```
column = []
solarray = []
for i in range(4):
for j in range(4):
sol = [i,j]
solarray.append(sol)
column.append(solarray)
print('Here is the last 1x2 list')
print(sol)
print('')
print('Here is the list containing all of the 1x2 lists')
print(solarray)
print('')
print('Here is the list containing the 4 lists of 1x2 lists')
print(column)
```
有一个输出:
```
'Here is the last 1x2 list'
[3, 3]
'Here is the list containing all of the 1x2 lists'
[[0, 3], [1, 3], [2, 3], [3, 3]]
'Here is the list containing the 4 lists of all 1x2 lists'
[[[0, 3], [1, 3], [2, 3], [3, 3]], [[0, 3], [1, 3], [2, 3], [3, 3]], [[0, 3], [1, 3], [2, 3], [3, 3]], [[0, 3], [1, 3], [2, 3], [3, 3]]]
```
另外请注意,我没有在代码中指定 1x2 数组,而是指定了一个列表,因为这是获得这个接近答案的唯一方法。此外,我的版本给出了最终的 j 索引,而不是在循环通过指定范围时遍历 j 的索引。
我做错了什么?
【问题讨论】:
-
solarray.append(sol)应该缩进。 -
当我这样做时,我将所有八个 1x2 列表放在一个列表中,并且没有以我在开头显示的这种伪矩阵索引样式进行分隔。目标是让最后一个打印语句在开始时显示我想要的内容。
-
已经回答了,但原因是
solarray不断增长。它需要在第一个循环中重新分配给[]。
标签: python for-loop arraylist indexing