python - multiply and add each element in list a with list b

前端 未结 3 719
灰色年华
灰色年华 2021-01-29 10:53

function:

def unique_common(a, b):

I have two lists, lets say:

a = [2, 3, 5, 7, 9] 

and another list

b = [5, 8         


        
相关标签:
3条回答
  • 2021-01-29 11:34

    Perhaps the solution would be to use NumPy, where the code should be very self-explanatory :

    import numpy as np
    
    a = np.array([2,3,5,7,9])
    b = np.array([5,8,4,1,11])
    
    c = a*b
    d = np.sum(c)
    print(d)
    
    0 讨论(0)
  • 2021-01-29 11:42

    With sum and zip:

    >>> a = [2, 3, 5, 7, 9]
    >>> b = [5, 8, 4, 1, 11]
    >>> sum(count*price for count, price in zip(a,b))
    160
    

    could you please tell how to give a lists a and b as parameters to a function like def unique_common(a, b)

    >>> def total_price(a, b):
    ...     return sum(count*price for count, price in zip(a,b))
    ... 
    >>> a = [2, 3, 5, 7, 9]
    >>> b = [5, 8, 4, 1, 11]
    >>> total_price(a, b)
    160
    
    0 讨论(0)
  • 2021-01-29 11:50

    And also you can use map :

    >>> a = [2, 3, 5, 7, 9] 
    >>> b = [5, 8, 4, 1, 11]
    >>> sum(map(lambda x: x[0] * x[1], zip(a, b)))
    160
    
    0 讨论(0)
提交回复
热议问题