请问如何在python中创建矩阵??
我想写一个函数,它以矩阵、描述单元格坐标的2个整数和将相应单元格设置为值的值作为参数?
请帮帮我
# 回答1
也许这会有所帮助:
也许这会有所帮助:
选择 | 换行 | 行号
- # A simple matrix
- # This matrix is a list of lists
- # Column and row numbers start with 1
- class Matrix(object):
- def __init__(self, cols, rows):
- self.cols = cols
- self.rows = rows
- # initialize matrix and fill with zeroes
- self.matrix = []
- for i in range(rows):
- ea_row = []
- for j in range(cols):
- ea_row.append(0)
- self.matrix.append(ea_row)
- def setitem(self, col, row, v):
- self.matrix[col-1][row-1] = v
- def getitem(self, col, row):
- return self.matrix[col-1][row-1]
- def __repr__(self):
- outStr = ""
- for i in range(self.rows):
- outStr += 'Row %s = %s\n' % (i+1, self.matrix[i])
- return outStr
- a = Matrix(4,4)
- print a
- a.setitem(3,4,'55.75')
- print a
- a.setitem(2,3,'19.1')
- print a
- print a.getitem(3,4)
产出:
选择 | 换行 | 行号
- >>> Row 1 = [0, 0, 0, 0]
- Row 2 = [0, 0, 0, 0]
- Row 3 = [0, 0, 0, 0]
- Row 4 = [0, 0, 0, 0]
- Row 1 = [0, 0, 0, 0]
- Row 2 = [0, 0, 0, 0]
- Row 3 = [0, 0, 0, '55.75']
- Row 4 = [0, 0, 0, 0]
- Row 1 = [0, 0, 0, 0]
- Row 2 = [0, 0, '19.1', 0]
- Row 3 = [0, 0, 0, '55.75']
- Row 4 = [0, 0, 0, 0]
- 55.75
- >>>
# 回答2
下面是"Matrix"的一个迭代器方法:
下面是"Matrix"的一个迭代器方法:
选择 | 换行 | 行号
- def __iter__(self):
- for row in range(self.rows):
- for col in range(self.cols):
- yield (self.matrix, row, col)
互动:
选择 | 换行 | 行号
- >>> a = Matrix(3,3)
- >>> x = 1.5
- >>> for i,r,c in a:
- ... x = x*2
- ... i[r][c] = x
- ...
- >>> a
- Row 1 = [3.0, 6.0, 12.0]
- Row 2 = [24.0, 48.0, 96.0]
- Row 3 = [192.0, 384.0, 768.0]
- >>>
# 回答3
@bvdet
我想做一些与矩阵的列相关的事情,我使用的是与创建的相同的类,请帮助我使用一个函数来获得第i列
@bvdet
我想做一些与矩阵的列相关的事情,我使用的是与创建的相同的类,请帮助我使用一个函数来获得第i列
# 回答4
这应该会起到作用:
这应该会起到作用:
选择 | 换行 | 行号
- def getcolumn(self, col):
- return [self.matrix[col-1][i] for i in range(self.rows)]
# 回答5
顺便说一句,NumPy有一个执行上述操作的矩阵对象,并且还支持矩阵运算
顺便说一句,NumPy有一个执行上述操作的矩阵对象,并且还支持矩阵运算
标签: python