Python 3:在没有 NumPy 的情况下将向量乘以矩阵

Python 3:在没有 NumPy 的情况下将向量乘以矩阵

问题描述:

我对 Python 还很陌生,正在尝试创建一个函数来将向量乘以矩阵(任何列大小).例如:

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]

这是我的代码:

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  

问题是,当我尝试选择矩阵 (r[j]) 中每列的第一行时,会显示错误列表索引超出范围".有没有其他不使用 NumPy 完成乘法的方法?

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?

Numpythonic 方法:(使用 numpy.dot 以获得两个矩阵的点积)

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])

Pythonic 方法:

The Pythonic approach:

你的第二个 for 循环的长度是 len(v) 并且你试图基于它索引 v 所以你得到了索引错误.作为一种更pythonic的方式,您可以使用 zip 函数来获取列表的列,然后在列表理解中使用 starmapmul :>

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]