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


当前回答

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

import numpy as np

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

其他回答

只想添加一个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中更复杂的部分,你可以使用一个简单的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

在这个帖子里有很多很好的答案。如果您想在实际生产中进行列表相乘,我建议使用标准numpy或math包。

如果你只是在寻找一个快速而肮脏的解决方案,你不想导入任何东西,你可以这样做:

l = [1,2,3,4,5,6]

def list_multiply(l):
    return eval('*'.join(map(str,l)))
    
print(list_multiply(l))
#Output: 720

Map (str,l)将列表中的每个元素转换为字符串。Join将每个元素组合成一个由*符号分隔的字符串。Eval将字符串转换回可以求值的函数。

警告:使用eval被认为是危险的,特别是当程序接受用户输入时,因为用户可能会向代码中注入任何函数并危及您的系统。

简单的方法是:

import numpy as np
np.exp(np.log(your_array).sum())