列表没有任何理由成为元组.虫子还是我太粗心了?

ong*_*kwu 3 python python-2.7

我现在陷入了困境.这段代码看起来很有效,但无论我多少次尝试更改它的语法,它仍然给我相同的结果.

基本上,我的问题是,即使我已经创建了一个列表嵌套列表nxn矩阵,当我尝试为特定行中的条目赋值时,我得到一个TypeError即

TypeError: 'tuple' object does not support item assignment
Run Code Online (Sandbox Code Playgroud)

我正在使用Python 2.7.我认为这是我的错,而不是Python的错误.我需要澄清一下.请尝试代码并告诉我它是否适用于您的com,如果没有,请详细说明问题,如果可以的话.提前致谢.

这是代码

import sys

class Matrix:
    def __init__(self, n):
    """create n x n matrix"""
        self.matrix = [[0 for i in range(n)] for i in range(n)]
        self.n = n

    def SetRow(self, i, x):
    """convert all entries in ith row to x"""
        for entry in range(self.n):
            self.matrix[i][entry] = x

    def SetCol(self, j, x):
    """convert all entries in jth column to x"""
        self.matrix = zip(*self.matrix)
        self.SetRow(j, x)
        self.matrix = zip(*self.matrix)

    def QueryRow(self, i):
    """print the sum of the ith row"""
        print sum(self.matrix[i])

    def QueryCol(self, j):
    """print the sum of the jth column"""
        self.matrix = zip(*self.matrix)
        x = sum(matrix[j])
        self.matrix = zip(*self.matrix)
        print x

mat = Matrix(256) # create 256 x 256 matrix

with open(sys.argv[1]) as file: # pass each line of file
    for line in file:
        ls = line.split(' ')
        if len(ls) == 2:
            query, a = ls
            eval('mat.%s(%s)' %(query, a))
        if len(ls) == 3:
            query, a, b = ls
            eval('mat.%s(%s, %s)' % (query, a, b))
Run Code Online (Sandbox Code Playgroud)

文件创建者脚本在这里:

file = open('newfile', 'w')
file.write("""SetCol 32 20
SetRow 15 7
SetRow 16 31
QueryCol 32
SetCol 2 14
QueryRow 10
SetCol 14 0
QueryRow 15
SetRow 10 1
QueryCol 2""")
file.close()
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 6

zip() 返回元组:

>>> zip([1, 2], [3, 4])
[(1, 3), (2, 4)]
Run Code Online (Sandbox Code Playgroud)

将它们映射回列表:

self.matrix = map(list, zip(*self.matrix))
Run Code Online (Sandbox Code Playgroud)