给定一个像[1,2,3,4,5,6]这样的数字列表,我如何编写代码将它们相乘,即计算1*2*3*4*5*6?
当前回答
只想添加一个Python 3.8的一行回答:
def multiply(l):
return [b := 1, [b := b * a for a in l]][-1][-1]
print(multiply([2, 3, 8, 10]))
输出:
480
解释:
[b:= 1,用于定义临时变量。 ...[b:= b * a for a in l]用于遍历列表并将b乘以每个元素 ...[1][1]是因为最终名单[b, [b * l [0], b * l[1],…, b * l[-1]]]。所以最后位置的元素是列表中所有元素的乘积。
其他回答
只想添加一个Python 3.8的一行回答:
def multiply(l):
return [b := 1, [b := b * a for a in l]][-1][-1]
print(multiply([2, 3, 8, 10]))
输出:
480
解释:
[b:= 1,用于定义临时变量。 ...[b:= b * a for a in l]用于遍历列表并将b乘以每个元素 ...[1][1]是因为最终名单[b, [b * l [0], b * l[1],…, b * l[-1]]]。所以最后位置的元素是列表中所有元素的乘积。
nums = str(tuple([1,2,3]))
mul_nums = nums.replace(',','*')
print(eval(mul_nums))
这是我的机器的一些性能测量。适用于长时间运行的循环中的小输入:
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))
在Python 3.8及以上版本中,数学标准库模块为此提供了.prod:
数学。Prod(可迭代,*,start=1)
该方法返回起始值(默认值:1)乘以数字可迭代对象的乘积:
import math
math.prod([1, 2, 3, 4, 5, 6])
# 720
如果可迭代对象为空,将产生1(或者起始值,如果提供)。