use*_*724 0 python rows matrix
我想创建一个2x3矩阵.(2行,3列)当我运行我的代码时,我在括号中得到矩阵,这是不正确的.
def fill_matrix(numrows, numcols, val):
matrix = [[val for i in range(numrows)] for j in range(numcols)]
return (numrows, numcols, val)
Run Code Online (Sandbox Code Playgroud)
如果我选择创建一个2x2矩阵并用1填充所有漏洞,我应该得到这个:[[1,1],[1,1]]
但我得到了这个:(2,2,1)
你的fill_matrix
函数返回元组(numrows, numcols, val)
,这就是你得到的原因(2,2,1)
.你根本没有返回矩阵.
你可以尝试:
def fill_matrix(numrows, numcols, val):
return [[val for i in range(numrows)] for j in range(numcols)]
Run Code Online (Sandbox Code Playgroud)
只返回矩阵本身.
如果您正在使用matricies,您可能还会考虑使用numpy并执行:
import numpy as np
np.ones((2,2))
Run Code Online (Sandbox Code Playgroud)
要么:
def fill_matrix(numrows, numcols, val):
return np.ones((numrows, numcols)) * val
Run Code Online (Sandbox Code Playgroud)