创建一个函数,用PYTHON中的所有元素创建一个新的universum[0]

2024-05-23 16:56:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在matlab中创建一个名为create\u empty\u universum的函数。这个函数将生成一个所有元素都为零的新宇宙。这个宇宙必须有给定矩阵的nxm(行的n长,列的m长)

例如。你知道吗

I have a matrix m given.

I = len(m)                                  #I is the amount of rows 
J = len(m[0])                               #J is the amount of columns
New_matrix =[]
row= I*[0]
index = 0

def create_empty_universum():
    while index < J :
        New_matrix.append(row)
        index +=1
    return New_matrix

但我的新矩阵仍然是[]这是怎么来的?你知道吗


Tags: ofthe函数newindexleniscreate
1条回答
网友
1楼 · 发布于 2024-05-23 16:56:38

要在列表上使用乘法运算符:

>>> cols = 4
>>> rows = 3
>>> [0] * cols
[0, 0, 0, 0]
>>> [[0] * cols] * rows
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

如果确实要使用助手函数:

def create_empty_universum(cols, rows, cell=0):
    return [[cell] * cols] * rows

更新:

请参阅@tobias_k的评论:您应该使用[[0]*cols for i in range(rows)]来拥有不相关的行。你知道吗

相关问题 更多 >