【问题标题】:creating a function that makes a new universum with all elements [0] PYTHON创建一个函数,用所有元素创建一个新的universum [0] PYTHON
【发布时间】:2013-03-12 19:05:22
【问题描述】:

我想在 matlab 中创建一个名为 create_empty_universum 的函数。这个函数将产生一个所有元素都为零的新universum。这个universum必须具有给定矩阵的n x m(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

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

【问题讨论】:

  • 您的return 不在您的职能范围内
  • 只是我,还是将变量命名为 New 非常令人不安?
  • 我解决了退货问题。但我的新矩阵仍然 []
  • index 不在create_empty_universum 的范围内——你怎么称呼它? 你还叫它吗?
  • New_matrix

标签: python matrix multidimensional-array


【解决方案1】:

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

>>> 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)] 来拥有不相关的行。

【讨论】:

  • 警告:这样做,矩阵将包含三倍的 same 列表,例如将 M[0][0] 设置为 5 也会将 M[1][0] 和 M[2][0]` 设置为 5。为避免这种情况,请使用 [[0]*cols for i in range(rows)]。 (对于内部列表,* 运算符很好。)
猜你喜欢
  • 1970-01-01
  • 2018-02-25
  • 1970-01-01
  • 2019-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-01
相关资源
最近更新 更多