【问题标题】:Creating a matrix using lists Python使用列表 Python 创建矩阵
【发布时间】:2015-12-05 23:19:32
【问题描述】:

在 Python 中,可以使用嵌套列表创建矩阵。例如,[[1, 2], [3, 4]]。下面我编写了一个函数,提示用户输入方阵的尺寸,然后提示用户输入 for 循环中的值。我有一个 tempArray 变量,它临时存储一行值,然后在附加到矩阵数组后被删除。出于某种原因,当我在最后打印矩阵时,我得到的是:[ [ ],[ ] ]。出了什么问题?

def proj11_1_a():
    n = eval(input("Enter the size of the square matrix: "))
    matrix = []
    tempArray = []   

    for i in range(1, (n**2) + 1):
        val = eval(input("Enter a value to go into the matrix: "))

        if i % n == 0:
            tempArray.append(val)
            matrix.append(tempArray)
            del tempArray[:]
        else:
            tempArray.append(val)
    print(matrix)
proj11_1_a()

【问题讨论】:

  • 这段代码没有打印
  • 对不起,我删除了那行
  • 为什么要删除阵列? del tempArray[:]
  • 数组只有一行值后才会被删除。删除它的原因是它可以存储下一行值,然后将其附加到矩阵数组中。

标签: python matrix


【解决方案1】:

您只需删除数组元素del tempArray[:],因为列表是可变的,它也会清除matrix的一部分

def proj11_1_a():
    n = eval(input("Enter the size of the square matrix: "))
    matrix = []
    tempArray = []   

    for i in range(1, (n**2) + 1):
        val = eval(input("Enter a value to go into the matrix: "))

        if i % n == 0:
            tempArray.append(val)
            matrix.append(tempArray)
            tempArray = [] #del tempArray[:]
        else:
            tempArray.append(val)
    print(matrix)
proj11_1_a()

可以进一步简化/清除为

def proj11_1_a():
    # Using eval in such place does not seem a good idea
    # unless you want to accept things like "2*4-2"
    # You might also consider putting try: here to check for correctness

    n = int(input("Enter the size of the square matrix: "))
    matrix = []

    for _ in range(n): 
        row = []   

        for _ in range(n): 
            # same situation as with n
            value = float(input("Enter a value to go into the matrix: "))
            row.append(value)

        matrix.append(row)

    return matrix

【讨论】:

  • 无论如何你都会做 append(val) 所以最好从 if/else 块中取出来
  • @Jjpx - OP 代码,只有导致问题的片段被更改,这里有很多可以改进的地方
  • 正如@Jjpx 所建议的,您也可以提供最佳版本。我认为拥有这两个版本对 OP 是有益的。
【解决方案2】:

另一种解决方案是更改以下行:

matrix.append(tempArray)

到:

matrix.append(tempArray.copy())

【讨论】:

  • 这是次优的,因为您需要...复制对象(因此,如果它很大,则需要线性时间)。
  • 由于最初的目的是提示用户输入,与用户输入的速度相比,开销是最小的。
  • 当然,但这并不意味着人们应该在其他地方编写不足的代码。我们也不应该向学习 Python 的人推荐它(比如 OP)
猜你喜欢
  • 2016-07-29
  • 2016-05-27
  • 2014-06-20
  • 2015-01-19
  • 2017-09-08
  • 2020-11-24
  • 1970-01-01
  • 2011-10-13
  • 1970-01-01
相关资源
最近更新 更多