给定一个像[1,2,3,4,5,6]这样的数字列表,我如何编写代码将它们相乘,即计算1*2*3*4*5*6?


当前回答

nums = str(tuple([1,2,3]))
mul_nums = nums.replace(',','*')
print(eval(mul_nums))

其他回答

我个人喜欢这样一个函数,它将泛型列表的所有元素相乘:

def multiply(n):
    total = 1
    for i in range(0, len(n)):
        total *= n[i]
    print total

它很紧凑,使用简单的东西(一个变量和一个for循环),对我来说感觉很直观(它看起来像我想到的问题,只是取一个,乘以它,然后乘以下一个,等等!)

我会使用numpy。执行任务的提示:

import numpy as np

mylist = [1, 2, 3, 4, 5, 6] 
result = np.prod(np.array(mylist))  

这是我的机器的一些性能测量。适用于长时间运行的循环中的小输入:

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中的溢出。

如果你想避免导入任何东西,避免Python中更复杂的部分,你可以使用一个简单的for循环:

nums = [1, 2, 3]

product = 1  # Don't use 0 here, otherwise, you'll get zero 
             # because anything times zero will be zero.
for num in nums:
    product *= num

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