What is the pythonic way to calculate dot product?

后端 未结 10 896
无人及你
无人及你 2020-12-08 00:39

I have two lists, one is named as A, another is named as B. Each element in A is a triple, and each element in B is just an number. I would like to calculate the result defi

10条回答
  •  春和景丽
    2020-12-08 01:15

    This might be repeated solution, however:

    >>> u = [(1, 2, 3), (4, 5, 6)]
    >>> v = [3, 7]
    

    In plain Python:

    >>> sum([x*y for (x, *x2), y in zip(u,v)])
    31
    

    Or using numpy (as described in user57368's answer) :

    import numpy as np
    >>> np.dot(np.array(u)[:,0], v)
    31
    

提交回复
热议问题