python创建矩阵无numpy,Python 3:将向量乘以没有NumPy的矩阵

I'm fairly new to Python and trying to create a function to multiply a vector by a matrix (of any column size).

e.g.:

multiply([1,0,0,1,0,0], [[0,1],[1,1],[1,0],[1,0],[1,1],[0,1]])

[1, 1]

Here is my code:

def multiply(v, G):

result = []

total = 0

for i in range(len(G)):

r = G[i]

for j in range(len(v)):

total += r[j] * v[j]

result.append(total)

return result

The problem is that when I try to select the first row of each column in the matrix (r[j]) the error 'list index out of range' is shown. Is there any other way of completing the multiplication without using NumPy?

解决方案

The Numpythonic approach: (using numpy.dot in order to get the dot product of two matrices)

In [1]: import numpy as np

In [3]: np.dot([1,0,0,1,0,0], [[0,1],[1,1],[1,0],[1,0],[1,1],[0,1]])

Out[3]: array([1, 1])

The Pythonic approach:

The length of your second for loop is len(v) and you attempt to indexing v based on that so you got index Error . As a more pythonic way you can use zip function to get the columns of a list then use starmap and mul within a list comprehension:

In [13]: first,second=[1,0,0,1,0,0], [[0,1],[1,1],[1,0],[1,0],[1,1],[0,1]]

In [14]: from itertools import starmap

In [15]: from operator import mul

In [16]: [sum(starmap(mul, zip(first, col))) for col in zip(*second)]

Out[16]: [1, 1]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值