简体   繁体   English

Python按元素逐个增加列表列表

[英]Python multiply list of lists element-wise

What is the neatest way to multiply element-wise a list of lists of numbers? 最简单的方法是将元素列表与元素列表相乘?

Eg 例如

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

-> [6,24,60]

Use np.prod : 使用np.prod

>>> a = np.array([[1,2,3],[2,3,4],[3,4,5]])
>>> np.prod(a,axis=1)
array([ 6, 24, 60])

Use a list comprehension and reduce : 使用列表理解并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]
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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM