【问题标题】:Can someone say what went wrong in this code?有人可以说这段代码出了什么问题吗?
【发布时间】:2018-03-08 01:31:28
【问题描述】:

我正在解决一个问题,它以数字、行、列作为参数并返回大小为行 x 列的结果矩阵。

def matrixReshape(self, nums, r, c):
    """
    :type nums: List[List[int]]
    :type r: int
    :type c: int
    :rtype: List[List[int]]
    """
    count = 0
    i = j = 0
    m = [[0]*c]*r
    for row in nums:
        for val in row:
            if j < c and i < r:
                print(val,m[i][j], i, j)
                m[i][j] = val
                print(val,m[i][j], i, j)
                count += 1
                j += 1
                if j == c:
                    i += 1
                    j = 0  
    if count == (r*c):
        return m
    else:
        return nums

当我测试像 ([[1,2],[3,4]], 4, 1) 这样的输入时,它会生成输出 [[4],[4],[4],[4]] 而不是[[1],[2],[3],[4]]

【问题讨论】:

  • edit你的问题标题是有意义的。它应该以对在搜索结果列表中查看它的未来读者有用的方式描述您提出的问题或问题。您当前的标题具有零意义。谢谢。

标签: python arrays arraylist


【解决方案1】:
m = [[0]*c]*r

这将创建一个r 引用的列表,该引用指向同一内部列表。因此,每当您修改 m[0] 时,您也在修改 m[1] 等等,因为它们是同一个列表。

你可能想要这样的东西:

m = [[0 for _ in range(c)] for _ in range(r)]

【讨论】:

    【解决方案2】:

    [0]*4 为您提供 相同 对象的四个副本,而不是四个独立的列表。

    试试

    m = [[0 for i in range(c)] for j in range(r)]
    

    【讨论】:

      猜你喜欢
      • 2022-12-16
      • 2020-02-21
      • 2020-10-30
      • 2010-11-08
      • 1970-01-01
      • 1970-01-01
      • 2020-05-02
      • 1970-01-01
      相关资源
      最近更新 更多