给定一个像[1,2,3,4,5,6]这样的数字列表,我如何编写代码将它们相乘,即计算1*2*3*4*5*6?
当前回答
你可以使用:
import operator
import functools
functools.reduce(operator.mul, [1,2,3,4,5,6], 1)
参见约简和算子。Mul文档进行解释。
你需要在Python 3+中导入functools行。
其他回答
你可以使用:
import operator
import functools
functools.reduce(operator.mul, [1,2,3,4,5,6], 1)
参见约简和算子。Mul文档进行解释。
你需要在Python 3+中导入functools行。
这是我的机器的一些性能测量。适用于长时间运行的循环中的小输入:
import functools, operator, timeit
import numpy as np
def multiply_numpy(iterable):
return np.prod(np.array(iterable))
def multiply_functools(iterable):
return functools.reduce(operator.mul, iterable)
def multiply_manual(iterable):
prod = 1
for x in iterable:
prod *= x
return prod
sizesToTest = [5, 10, 100, 1000, 10000, 100000]
for size in sizesToTest:
data = [1] * size
timerNumpy = timeit.Timer(lambda: multiply_numpy(data))
timerFunctools = timeit.Timer(lambda: multiply_functools(data))
timerManual = timeit.Timer(lambda: multiply_manual(data))
repeats = int(5e6 / size)
resultNumpy = timerNumpy.timeit(repeats)
resultFunctools = timerFunctools.timeit(repeats)
resultManual = timerManual.timeit(repeats)
print(f'Input size: {size:>7d} Repeats: {repeats:>8d} Numpy: {resultNumpy:.3f}, Functools: {resultFunctools:.3f}, Manual: {resultManual:.3f}')
结果:
Input size: 5 Repeats: 1000000 Numpy: 4.670, Functools: 0.586, Manual: 0.459
Input size: 10 Repeats: 500000 Numpy: 2.443, Functools: 0.401, Manual: 0.321
Input size: 100 Repeats: 50000 Numpy: 0.505, Functools: 0.220, Manual: 0.197
Input size: 1000 Repeats: 5000 Numpy: 0.303, Functools: 0.207, Manual: 0.185
Input size: 10000 Repeats: 500 Numpy: 0.265, Functools: 0.194, Manual: 0.187
Input size: 100000 Repeats: 50 Numpy: 0.266, Functools: 0.198, Manual: 0.185
您可以看到,Numpy在较小的输入上要慢得多,因为它在执行乘法之前分配一个数组。另外,要注意Numpy中的溢出。
今天发现了这个问题,但我注意到它没有在列表中有None的情况。所以,完整的解决方案是:
from functools import reduce
a = [None, 1, 2, 3, None, 4]
print(reduce(lambda x, y: (x if x else 1) * (y if y else 1), a))
在加法的情况下,我们有:
print(reduce(lambda x, y: (x if x else 0) + (y if y else 0), a))
我个人喜欢这样一个函数,它将泛型列表的所有元素相乘:
def multiply(n):
total = 1
for i in range(0, len(n)):
total *= n[i]
print total
它很紧凑,使用简单的东西(一个变量和一个for循环),对我来说感觉很直观(它看起来像我想到的问题,只是取一个,乘以它,然后乘以下一个,等等!)
Python 3:使用functools.reduce:
>>> from functools import reduce
>>> reduce(lambda x, y: x*y, [1, 2, 3, 4, 5, 6])
720
Python 2:使用reduce:
>>> reduce(lambda x, y: x*y, [1, 2, 3, 4, 5, 6])
720
为了兼容2和3,请使用Six (pip install Six),然后:
>>> from six.moves import reduce
>>> reduce(lambda x, y: x*y, [1,2,3,4,5,6])
720
推荐文章
- Numpy Max vs amax vs maximum
- 我应该在.gitignore文件中添加Django迁移文件吗?
- 每n行有熊猫
- 实例属性attribute_name定义在__init__之外
- 如何获取在Python中捕获的异常的名称?
- 第一次出现的值大于现有值的Numpy
- 如何从Python函数中返回两个值?
- 前一个月的Python日期
- Python中方括号括起来的列表和圆括号括起来的列表有什么区别?
- Python日志记录不输出任何东西
- 每n秒运行特定代码
- SQLAlchemy是否有与Django的get_or_create等价的函数?
- 如何将python datetime转换为字符串,具有可读格式的日期?
- 美丽的汤和提取div及其内容的ID
- 在Python中重置生成器对象