【问题标题】:Constructing a list of list of arrays?构造数组列表的列表?
【发布时间】: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


【解决方案1】:
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)

【讨论】:

  • 我要哭了!谢谢!
【解决方案2】:

您需要在外循环内初始化solarray 并按照建议缩进。

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

print(column)

这将产生你想要的:

In [5]: print(column)
[[[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]]]

干杯!

ps。为了便于阅读,我手动在输出中添加了一些内容

【讨论】:

    【解决方案3】:

    使用列表理解。

    solarray = [ [ [a,b] for b in range(4) ] for a in range(4) ]
    

    【讨论】:

    • 这也有效。我很羡慕那些可以编写非常 Pythonic 代码的人。感谢您的帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多