如何将列表中的所有项目与 Python 相乘?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13840379/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 09:43:32  来源:igfitidea点击:

How can I multiply all items in a list together with Python?

pythonlistmultiplication

提问by user1897814

I need to write a function that takes a listof numbers and multipliesthem together. Example: [1,2,3,4,5,6]will give me 1*2*3*4*5*6. I could really use your help.

我需要编写一个函数,该函数接受一个数字列表并将它们相乘。例子: [1,2,3,4,5,6]会给我1*2*3*4*5*6。我真的可以使用你的帮助。

回答by icecrime

You can use:

您可以使用:

import operator
import functools
functools.reduce(operator.mul, [1,2,3,4,5,6], 1)

See reduceand operator.muldocumentations for an explanation.

有关解释,请参阅reduceoperator.mul文档。

You need the import functoolsline in Python 3+.

您需要import functoolsPython 3+ 中的这一行。

回答by rich tier

Python 3: use functools.reduce:

Python 3:使用functools.reduce

>>> from functools import reduce
>>> reduce(lambda x, y: x*y, [1,2,3,4,5,6])
720

Python 2: use reduce:

Python 2:使用reduce

>>> reduce(lambda x, y: x*y, [1,2,3,4,5,6])
720

For compatible with 2 and 3 use pip install six, then:

为了与 2 和 3 兼容,使用pip install six,然后:

>>> from six.moves import reduce
>>> reduce(lambda x, y: x*y, [1,2,3,4,5,6])
720

回答by DeadChex

If you want to avoid importing anything and avoid more complex areas of Python, you can use a simple for loop

如果你想避免导入任何东西并避免 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

回答by user5038135

I personally like this for a function that multiplies all elements of a generic list together:

对于将通用列表的所有元素相乘的函数,我个人喜欢这个:

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

It's compact, uses simple things (a variable and a for loop), and feels intuitive to me (it looks like how I'd think of the problem, just take one, multiply it, then multiply by the next, and so on!)

它很紧凑,使用简单的东西(一个变量和一个 for 循环),对我来说感觉很直观(它看起来像我如何看待这个问题,只需取一个,乘以它,然后乘以下一个,依此类推! )

回答by belindanju

I would use the numpy.prodto perform the task. See below.

我会用numpy.prod来执行任务。见下文。

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

回答by Shakti Nandan

I would like this in following way:

我想通过以下方式:

    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

回答by Xxxo

Found this question today but I noticed that it does not have the case where there are None's in the list. So, the complete solution would be:

今天发现这个问题,但我注意到它没有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))

In the case of addition, we have:

在加法的情况下,我们有:

print(reduce(lambda x, y: (x if x else 0) + (y if y else 0), a))

回答by M. Dickson

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

回答by Disenchanted

Here's some performance measurements from my machine. Relevant in case this is performed for small inputs in a long-running loop:

这是我的机器的一些性能测量。如果在长时间运行的循环中为小输入执行此操作,则相关:

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}')

Results:

结果:

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

You can see that Numpy is quite a bit slower on smaller inputs, since it allocates an array before multiplication is performed. Also, watch out for the overflow in Numpy.

您可以看到 Numpy 在较小的输入上要慢很多,因为它在执行乘法之前分配了一个数组。另外,请注意 Numpy 中的溢出。

回答by XXinyue

The simple way is:

简单的方法是:

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