Python 3.x 如何对此使用列表理解?
我想输入两个数字:行数和列数。然后我想用它们来输出一个按顺序编号的矩阵。我想用一个列表来做这件事。以下是可能的输出Python 3.x 如何对此使用列表理解?,python-3.x,Python 3.x,我想输入两个数字:行数和列数。然后我想用它们来输出一个按顺序编号的矩阵。我想用一个列表来做这件事。以下是可能的输出 >>>> my_matrix = matrix_fill(3, 4) >>>> my_matrix [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] 我使用以下代码输出顺序编号的列表: def matrix_fill(num_rows, num_col): list=[i for
>>>> my_matrix = matrix_fill(3, 4)
>>>> my_matrix
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
我使用以下代码输出顺序编号的列表:
def matrix_fill(num_rows, num_col):
list=[i for i in range(num_col)]
return (list)
但是,我不知道如何使数字的顺序列表根据num_行分解为单独的列表,如输出中所示。将列表嵌套在另一个列表中,使用
itertools.count()
生成序列:
import itertools
rows = 3
cols = 4
count_gen = itertools.count() # pass start=1 if you need the sequence to start at 1
my_matrix = [[next(count_gen) for c in range(cols)] for r in range(rows)]
print(my_matrix)
# prints: [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]
# As a function
def matrix_fill(rows, cols):
count_gen = itertools.count()
return [[next(count_gen) for c in range(cols)] for r in range(rows)]
我想你不需要工具来做那件事。像这样:
def matrix_fill(rows,cols):
return [[x for x in range(1,rows*cols+1)][i:i+cols] for i in range(0,rows*cols,cols)]
然后它就如预期的那样工作了
>>> matrix_fill(3,4)
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
让我们把它分解一下,了解发生了什么
>>> [x for x in range(1,3*4+1)]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
所以我们要做的是每四个元素得到一个新的切片
>>> [x for x in range(1,3*4+1)][0:4]
[1, 2, 3, 4]
>>> [x for x in range(1,3*4+1)][4:8]
[5, 6, 7, 8]
>>> [x for x in range(1,3*4+1)][8:12]
[9, 10, 11, 12]
因此,我们希望迭代长度为“rows*cols”(3*4)的列表
[x代表x,范围为(1,3*4+1)]
中的元素,每“cols”个元素创建一个新片段,并将这些片段分组到单个列表下。因此,[[x代表范围内的x(1,行*cols+1)][i:i+cols]代表范围内的i(0,行*cols,cols)]
是一个合适的表达式 如果使用numpy
模块,该方法非常简单,不需要理解列表
my_matrix = np.arange(1, 13).reshape(3,4)
打印变量my_矩阵
显示
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
到目前为止你都尝试了什么?因为我会想到循环。但是,我想使用列表理解和无循环来完成这项工作,我只是无法理解。如果您能解释(范围(1,rowscols+1)中的x代表x)[I:I+cols]对于范围(0,rowscols,cols)中的I,我将不胜感激,因为我有点迷路了。