python - 构造数组列表的列表?
问题描述
在 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 。
我究竟做错了什么?
解决方案
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)
推荐阅读
- powershell - Powershell 脚本没有为 Test-NetConnection 提供输出(将在 UiPath 中调用)
- python - iter() 返回 'int' 类型的非迭代器
- python - 如何从 input() 函数中只获取单词而不是字符串
- relationship - 如何在 OctoberCMS 的数据透视表中设置附加列的值?
- python-3.x - Python:如何使用 setuptools 指定 entry_points 的优化级别?
- azure-cosmosdb - 在 Azure cosmos db 上写入 400kb - 600kb 的文档需要大量 RU
- reactjs - 如何将数据从自定义 TexInput 组件传递到主登录组件
- ssl - 如何在 tls 中使用 STM32 lwip/mqtt api?
- github - 如何在 github 操作中使用 GPG 密钥?
- python - PyTorch 张量高级索引