[英]How can I multiply all items in a list together with Python?
我需要编写一个 function,它接受一个数字列表并将它们相乘。 示例: [1,2,3,4,5,6]
会给我1*2*3*4*5*6
。 我真的需要你的帮助。
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 兼容,请使用pip install six
,然后:
>>> from six.moves import reduce
>>> reduce(lambda x, y: x*y, [1,2,3,4,5,6])
720
您可以使用:
import operator
import functools
functools.reduce(operator.mul, [1,2,3,4,5,6], 1)
有关解释,请参阅reduce
和operator.mul
文档。
您需要 Python 3+ 中的import functools
行。
我会使用numpy.prod
来执行任务。 见下文。
import numpy as np
mylist = [1, 2, 3, 4, 5, 6]
result = np.prod(np.array(mylist))
如果你想避免导入任何东西并避免 Python 的更复杂的领域,你可以使用一个简单的 for 循环
product = 1 # Don't use 0 here, otherwise, you'll get zero
# because anything times zero will be zero.
list = [1, 2, 3]
for x in list:
product *= x
从Python 3.8
开始,标准库中的math
模块中包含了一个.prod
函数:
math.prod(iterable, *, start=1)
该方法返回一个的产物start
值(默认值:1)倍的迭代数:
import math
math.prod([1, 2, 3, 4, 5, 6])
>>> 720
如果可迭代是空的,这将产生1
(或start
值,如果提供的话)。
这是我的机器的一些性能测量。 如果在长时间运行的循环中为小输入执行此操作,则相关:
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 中的溢出。
对于将通用列表的所有元素相乘的函数,我个人喜欢这个:
def multiply(n):
total = 1
for i in range(0, len(n)):
total *= n[i]
print total
它很紧凑,使用简单的东西(一个变量和一个 for 循环),对我来说感觉很直观(看起来我是如何看待这个问题的,只需取一个,乘以它,然后乘以下一个,依此类推! )
Numpy
有prod()
函数,它返回一个列表的乘积,或者在这种情况下,因为它是 numpy,它是给定轴上数组的乘积:
import numpy
a = [1,2,3,4,5,6]
b = numpy.prod(a)
...否则你可以只导入numpy.prod()
:
from numpy import prod
a = [1,2,3,4,5,6]
b = prod(a)
简单的方法是:
import numpy as np
np.exp(np.log(your_array).sum())
nums = str(tuple([1,2,3]))
mul_nums = nums.replace(',','*')
print(eval(mul_nums))
今天发现了这个问题,但我注意到它没有列表中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 product_list(p):
total =1 #critical step works for all list
for i in p:
total=total*i # this will ensure that each elements are multiplied by itself
return total
print product_list([2,3,4,2]) #should print 48
这是我的代码:
def product_list(list_of_numbers):
xxx = 1
for x in list_of_numbers:
xxx = xxx*x
return xxx
print(product_list([1,2,3,4]))
结果 : ('1*1*2*3*4', 24)
如何使用递归?
def multiply(lst):
if len(lst) > 1:
return multiply(lst[:-1])* lst[-1]
else:
return lst[0]
我的解决方案:
def multiply(numbers):
a = 1
for num in numbers:
a *= num
return a
只想添加一个 Python 3.10 单行答案:
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]]]
。 所以最后位置的元素是列表中所有元素的乘积。
这个线程中有很多好的答案。 如果您想在实际生产中乘以列表,我建议使用标准 numpy 或数学包。
如果您只是在寻找一个快速而肮脏的解决方案并且您不想导入任何东西,您可以这样做:
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
将字符串转换回可以计算的 function。
警告:使用eval
被认为是危险的,尤其是当程序接受用户输入时,因为用户可能会将任何 function 注入代码并危害您的系统。
'''理解for循环逻辑使用的唯一简单方法'''
Lap=[2,5,7,7,9] x=1 for i in Lap: x=i*x print(x)
很简单,不要导入任何东西。 这是我的代码。 这将定义一个函数,该函数将列表中的所有项目相乘并返回它们的乘积。
def myfunc(lst):
multi=1
for product in lst:
multi*=product
return product
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.