Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 构造数组列表?_Python_For Loop_Arraylist_Indexing - Fatal编程技术网

Python 构造数组列表?

Python 构造数组列表?,python,for-loop,arraylist,indexing,Python,For Loop,Arraylist,Indexing,在Python中,我试图创建一个列表,包含1x2数组的列表。我将如何使用for循环构建以下列表 这似乎是一个非常简单的问题,所以我尝试了许多嵌套循环方法来尝试创建它,但没有成功。下面是我最近的尝试 ``` column = [] solarray = [] for i in range(4): for j in range(4): sol = [i,j] solarray.appe

在Python中,我试图创建一个列表,包含1x2数组的列表。我将如何使用for循环构建以下列表

这似乎是一个非常简单的问题,所以我尝试了许多嵌套循环方法来尝试创建它,但没有成功。下面是我最近的尝试

```
    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)
solarray=[[a,b]表示范围(4)中的b]表示范围(4)中的a]

您需要在外部循环内初始化
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]]]
干杯


另外,为了可读性,我手动在输出中添加了一些。append(sol)应该缩进。当我这样做时,我在一个列表中得到了所有八个1x2列表,而不是在我开始时显示的伪矩阵索引样式中分开。我们的目标是让最后一个print语句显示我一开始想要的内容。它已经得到了回答,但原因是
solarray
不断增长。它需要在第一个循环中被重新分配到
[]
。我会哭的!非常感谢。这也行得通。我很羡慕那些可以编写非常python代码的人。谢谢你的帮助
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]]]