我是Python的新手,我需要在一个线程中创建一个矩阵,然后在第二个线程中将主对角线计算为一行和一列中的元素之和
matrix.py
class MyThread(Thread):
def __init__(self, number, logger):
Thread.__init__(self)
self.number = number
self.logger = logger
def run(self) :
if self.number == 0:
logger.debug('Calling martix()')
mat = matrix()
else:
logger.debug('Calling recalculate()')
recalculate(mat)
def matrix():
delimetr = "|"
print('Enter the size of matrix \n')
n = int(input())
print('start at:', ctime())
mat = [[randint(0,100) for j in range(n)] for i in range(n)]
print('Before')
for i in mat:
print(delimetr,*i,delimetr)
return mat
def get_logger():
logger = logging.getLogger("threading_matrix")
logger.setLevel(logging.DEBUG)
fh = logging.FileHandler("threading_matix.log")
fmt = '%(asctime)s - %(threadName)s - %(levelname)s - %(message)s'
formatter = logging.Formatter(fmt)
fh.setFormatter(formatter)
logger.addHandler(fh)
return logger
def recalculate(mat):
delimetr = "|"
m=0
score = 0;
n = len(mat)
for v in mat:
score = 0;
for i in range(n):
score = mat[m][i] + score
for b in range(n):
if b == m : continue
else:
score = mat[b][m] + score
mat[m][m] = score
m+=1
print('After')
for i in mat:
print(delimetr,*i,delimetr)
print('end at:',ctime())
if __name__ == '__main__':
logger = get_logger()
for i in range(2):
name = "Thread #%s" % (i+1)
thread = MyThread(i, logger)
thread.setName(name)
thread.start()
thread.join()
运行此命令时出现异常
in run recalculate(mat) UnboundLocalError: local variable 'mat' referenced before assignment
我试图将mat
设置为全局变量,但这无济于事。