请问如何在python中创建矩阵??

我想写一个函数,它以矩阵、描述单元格坐标的2个整数和将相应单元格设置为值的值作为参数?
请帮帮我

# 回答1


也许这会有所帮助:

选择 | 换行 | 行号
  1. # A simple matrix
  2. # This matrix is a list of lists
  3. # Column and row numbers start with 1
  4.  
  5. class Matrix(object):
  6.     def __init__(self, cols, rows):
  7.         self.cols = cols
  8.         self.rows = rows
  9.         # initialize matrix and fill with zeroes
  10.         self.matrix = []
  11.         for i in range(rows):
  12.             ea_row = []
  13.             for j in range(cols):
  14.                 ea_row.append(0)
  15.             self.matrix.append(ea_row)
  16.  
  17.     def setitem(self, col, row, v):
  18.         self.matrix[col-1][row-1] = v
  19.  
  20.     def getitem(self, col, row):
  21.         return self.matrix[col-1][row-1]
  22.  
  23.     def __repr__(self):
  24.         outStr = ""
  25.         for i in range(self.rows):
  26.             outStr += 'Row %s = %s\n' % (i+1, self.matrix[i])
  27.         return outStr
  28.  
  29.  
  30. a = Matrix(4,4)
  31. print a
  32. a.setitem(3,4,'55.75')
  33. print a
  34. a.setitem(2,3,'19.1')
  35. print a
  36. print a.getitem(3,4)

产出:

选择 | 换行 | 行号
  1. >>> Row 1 = [0, 0, 0, 0]
  2. Row 2 = [0, 0, 0, 0]
  3. Row 3 = [0, 0, 0, 0]
  4. Row 4 = [0, 0, 0, 0]
  5.  
  6. Row 1 = [0, 0, 0, 0]
  7. Row 2 = [0, 0, 0, 0]
  8. Row 3 = [0, 0, 0, '55.75']
  9. Row 4 = [0, 0, 0, 0]
  10.  
  11. Row 1 = [0, 0, 0, 0]
  12. Row 2 = [0, 0, '19.1', 0]
  13. Row 3 = [0, 0, 0, '55.75']
  14. Row 4 = [0, 0, 0, 0]
  15.  
  16. 55.75
  17. >>> 
# 回答2


下面是"Matrix"的一个迭代器方法:

选择 | 换行 | 行号
  1.     def __iter__(self):
  2.         for row in range(self.rows):
  3.             for col in range(self.cols):
  4.                 yield (self.matrix, row, col)  

互动:

选择 | 换行 | 行号
  1. >>> a = Matrix(3,3)
  2. >>> x = 1.5
  3. >>> for i,r,c in a:
  4. ...     x = x*2
  5. ...     i[r][c] = x
  6. ...     
  7. >>> a
  8. Row 1 = [3.0, 6.0, 12.0]
  9. Row 2 = [24.0, 48.0, 96.0]
  10. Row 3 = [192.0, 384.0, 768.0]
  11.  
  12. >>> 
# 回答3


@bvdet
我想做一些与矩阵的列相关的事情,我使用的是与创建的相同的类,请帮助我使用一个函数来获得第i列
# 回答4


这应该会起到作用:

选择 | 换行 | 行号
  1.     def getcolumn(self, col):
  2.         return [self.matrix[col-1][i] for i in range(self.rows)]
# 回答5


顺便说一句,NumPy有一个执行上述操作的矩阵对象,并且还支持矩阵运算

标签: python

添加新评论