首页 文章

使用列表Python创建矩阵

提问于
浏览
3

在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()

2 回答

  • 1

    你只需删除数组元素 del tempArray[:] ,因为列表是 mutable 它也清除部分 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
    
  • 2

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

    matrix.append(tempArray)
    

    至:

    matrix.append(tempArray.copy())
    

相关问题