What is the pythonic way to calculate dot product?

后端 未结 10 884
无人及你
无人及你 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:07

    Python 3.5 has an explicit operator @ for the dot product, so you can write

    a = A @ B
    

    instead of

    a = numpy.dot(A,B)
    
    0 讨论(0)
  • 2020-12-08 01:09
    import numpy
    result = numpy.dot( numpy.array(A)[:,0], B)
    

    http://docs.scipy.org/doc/numpy/reference/

    If you want to do it without numpy, try

    sum( [a[i][0]*b[i] for i in range(len(b))] )
    
    0 讨论(0)
  • 2020-12-08 01:14
    from operator import mul
    
    sum(map(mul, A, B))
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-08 01:16

    All above answers are correct, but in my opinion the most pythonic way to calculate dot product is:

    >>> a=[1,2,3]
    >>> b=[4,5,6]
    >>> sum(map(lambda pair:pair[0]*pair[1],zip(a,b)))
    32
    
    0 讨论(0)
  • 2020-12-08 01:19

    Using the operator and the itertools modules:

    from operator import mul
    from itertools import imap
    
    sum(imap(mul, A, B))
    
    0 讨论(0)
提交回复
热议问题