Python multiply list of lists element-wise

后端 未结 3 1015
醉梦人生
醉梦人生 2021-01-13 10:42

What is the neatest way to multiply element-wise a list of lists of numbers?

E.g.

[[1,2,3],[2,3,4],[3,4,5]]

-> [6,24,60]
相关标签:
3条回答
  • 2021-01-13 11:03
    import operator
    import functools
    answer = [functools.reduce(operator.mul, subl) for subl in L]
    

    Or, if you prefer map:

    answer = map(functools.partial(functools.reduce, operator.mul), L)  # listify as required
    
    0 讨论(0)
  • 2021-01-13 11:07

    Use np.prod:

    >>> a = np.array([[1,2,3],[2,3,4],[3,4,5]])
    >>> np.prod(a,axis=1)
    array([ 6, 24, 60])
    
    0 讨论(0)
  • 2021-01-13 11:12

    Use a list comprehension and reduce:

    >>> from operator import mul
    >>> lis = [[1,2,3],[2,3,4],[3,4,5]]
    >>> [reduce(mul, x) for x in lis]
    [6, 24, 60]
    
    0 讨论(0)
提交回复
热议问题