将CSR矩阵乘以向量 - python

我正在关注此stackoverflow帖子on csr matrix multiplication to a vector
并在python中实现它,并导致列表超出范围错误。

这是我的代码:

def MatrixMultiplication(data,row_ptr,col_ptr,vec):
  ResultMatrix =[]
  vec_len = len(vec)
  for i in range(0,vec_len):
    ResultMatrix.insert(i,0)
  for i in range(0,vec_len):
    start, end = row_ptr[i], row_ptr[i + 1]
    for k in range(start, end):
      ResultMatrix[i] = ResultMatrix[i]+data[k]*vec[col_ptr[k]]
  return ResultMatrix

data = [2, 4, 7, 1, 3, 2]
row_ptr =  [2,3 ,5, 5 ,6]
col_ptr = [1 ,3, 4, 0, 3, 3]
vec = [2,3, 5, 4, 2]

MatrixMultiplication(data,row_ptr,col_ptr,vec)

请帮我解决我要去的地方。

输出应为:[22 14 14 0 8]

错误:

IndexError: list index out of range
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<command-338158343473691> in <module>()
----> 1 MatrixMultiplication(data,row_ptr,col_ptr,vec)

<command-3658506804172571> in MatrixMultiplication(data, row_ptr, col_ptr, vec)
      5     ResultMatrix.insert(i,0)
      6   for i in range(0,vec_len):
----> 7     start, end = row_ptr[i], row_ptr[i + 1]
      8     for k in range(start, end):
      9       ResultMatrix[i] = ResultMatrix[i]+data[k]*vec[col_ptr[k]]

IndexError: list index out of range

仅供参考:

row_ptr的最后一个元素将是数据列表的大小

参考方案

该错误消息是很不言自明的:您正在尝试在高达row_ptr[i + 1](这是列表的长度)的for循环中访问vec_len。当您到达for循环和i = vec_len - 1的最后一次迭代时,然后是i + 1 = vec_len,它不在列表的范围内(请记住,Python列表是0初始化的)。

为防止出现此错误,您的范围仅应在第二个for循环中升至vec_len - 1

Python sqlite3数据库已锁定 - python

我在Windows上使用Python 3和sqlite3。我正在开发一个使用数据库存储联系人的小型应用程序。我注意到,如果应用程序被强制关闭(通过错误或通过任务管理器结束),则会收到sqlite3错误(sqlite3.OperationalError:数据库已锁定)。我想这是因为在应用程序关闭之前,我没有正确关闭数据库连接。我已经试过了: connectio…

Python pytz时区函数返回的时区为9分钟 - python

由于某些原因,我无法从以下代码中找出原因:>>> from pytz import timezone >>> timezone('America/Chicago') 我得到:<DstTzInfo 'America/Chicago' LMT-1 day, 18:09:00 STD…

用大写字母拆分字符串,但忽略AAA Python Regex - python

我的正则表达式:vendor = "MyNameIsJoe. I'mWorkerInAAAinc." ven = re.split(r'(?<=[a-z])[A-Z]|[A-Z](?=[a-z])', vendor) 以大写字母分割字符串,例如:'我的名字是乔。 I'mWorkerInAAAinc”变成…

如何打印浮点数的全精度[Python] - python

我编写了以下函数,其中传递了x,y的值:def check(x, y): print(type(x)) print(type(y)) print(x) print(y) if x == y: print "Yes" 现在当我打电话check(1.00000000000000001, 1.0000000000000002)它正在打印:<…

Python:如何根据另一列元素明智地查找一列中的空单元格计数? - python

df = pd.DataFrame({'user': ['Bob', 'Jane', 'Alice','Jane', 'Alice','Bob', 'Alice'], 'income…