将所有项目乘以Python中的所有项目

时间:2016-05-12 10:36:14

标签: python list multiplication

如何将列表中的项目相乘?

例如:

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

def multiplyListItems(l):
   # some code here...

预期的计算和返回值为1 x 2 x 3 x 4 x 5 = 120

3 个答案:

答案 0 :(得分:3)

一种方法是使用reduce

>>> num_list = [1,2,3,4,5]
>>> reduce(lambda x, y: x*y, num_list)
120

答案 1 :(得分:1)

使用functools.reduce,这更快(见下文),并且与Python 3更加向前兼容。

import operator
import functools

num_list = [1,2,3,4,5]
accum_value = functools.reduce(operator.mul, num_list)

print(accum_value)
# Output
120

以3种不同的方式衡量执行时间,

# Way 1: reduce
$ python -m timeit "reduce(lambda x, y: x*y, [1,2,3,4,5])"
1000000 loops, best of 3: 0.727 usec per loop

# Way 2: np.multiply.reduce
$ python -m timeit -s "import numpy as np" "np.multiply.reduce([1,2,3,4,5])"
100000 loops, best of 3: 6.71 usec per loop

# Way 3: functools.reduce
$ python -m timeit -s "import operator, functools" "functools.reduce(operator.mul, [1,2,3,4,5])"
1000000 loops, best of 3: 0.421 usec per loop

对于更大的列表,最好使用@MikeMüller提到的np.multiply.reduce

$ python -m timeit "reduce(lambda x, y: x*y, range(1, int(1e5)))"
10 loops, best of 3: 3.01 sec per loop

$ python -m timeit -s "import numpy as np" "np.multiply.reduce(range(1, int(1e5)))"
100 loops, best of 3: 11.2 msec per loop

$ python -m timeit -s "import operator, functools" "functools.reduce(operator.mul, range(1, int(1e5)))"
10 loops, best of 3: 2.98 sec per loop

答案 2 :(得分:1)

NumPy解决方案:

>>> import numpy as np
>>> np.multiply.reduce(num_list)
120

运行更大的列表:

In [303]:
from operator import mul
from functools import reduce
import numpy as np
​
a = list(range(1, int(1e5)))

In [304]
%timeit np.multiply.reduce(a)
100 loops, best of 3: 8.25 ms per loop

In [305]:
%timeit reduce(lambda x, y: x*y, a)
1 loops, best of 3: 5.04 s per loop

In [306]:
%timeit reduce(mul, a)
1 loops, best of 3: 5.37 s per loop

NumPy主要在C语言中实现。因此,它通常比在Python列表上编写循环快一到两个数量级。这适用于较大的阵列。如果一个数组很小并且它经常用于Python,那么事情可能比使用纯Python更慢。这是因为Python对象和C数据类型之间的开销转换。实际上,编写Python for循环来迭代NumPy数组是一种反模式。

这里,与增益相比,具有五个数字的列表会产生相当大的开销 来自更快的数字。