首页 > 解决方案 > 构造数组列表的列表?

问题描述

在 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 。

我究竟做错了什么?

标签: pythonfor-looparraylistindexing

解决方案


column = []
solarray = []

for i in range(4):
    solarray = []
    for j in range(4):
        solarray.append([i,j])
    column.append(solarray)

print('Here is the list containing the 4 lists of 1x2 lists')
print(column)

推荐阅读