## 问题：如何将列表中的所有项目与Python相乘？

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

## 回答 0

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``````

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

Python 3: use `functools.reduce`:

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

Python 2: use `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:

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

## 回答 1

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

You can use:

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

See `reduce` and `operator.mul` documentations for an explanation.

You need the `import functools` line in Python 3+.

## 回答 2

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

I would use the `numpy.prod` to perform the task. See below.

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

## 回答 3

``````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``````

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

``````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
``````

## 回答 4

`math.prod(iterable, *, start=1)`

``````import math
math.prod([1, 2, 3, 4, 5, 6])

>>> 720``````

Starting `Python 3.8`, a `.prod` function has been included to the `math` module in the standard library:

`math.prod(iterable, *, start=1)`

The method returns the product of a `start` value (default: 1) times an iterable of numbers:

``````import math
math.prod([1, 2, 3, 4, 5, 6])

>>> 720
``````

If the iterable is empty, this will produce `1` (or the `start` value, if provided).

## 回答 5

``````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``````

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.

## 回答 6

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

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!)

## 回答 7

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

The simple way is:

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

## 回答 8

`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)``````

`Numpy` has the `prod()` function that returns the product of a list, or in this case since it’s numpy, it’s the product of an array over a given axis:

``````import numpy
a = [1,2,3,4,5,6]
b = numpy.prod(a)
``````

…or else you can just import `numpy.prod()`:

``````from numpy import prod
a = [1,2,3,4,5,6]
b = prod(a)
``````

## 回答 9

``````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))``

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:

``````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))
``````

## 回答 10

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

## 回答 11

``````    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
print product_list([2,3,4,2]) #should print 48``````

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
print product_list([2,3,4,2]) #should print 48
``````

## 回答 12

``````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]))``````

This is my code:

``````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]))
``````

result : (‘1*1*2*3*4’, 24)

## 回答 13

``````def multiply(lst):
if len(lst) > 1:
return multiply(lst[:-1])* lst[-1]
else:
return lst[0]``````

``````def multiply(lst):
if len(lst) > 1:
return multiply(lst[:-1])* lst[-1]
else:
return lst[0]
``````

## 回答 14

``````def multiply(numbers):
a = 1
for num in numbers:
a *= num
return a

pass``````

My solution:

``````def multiply(numbers):
a = 1
for num in numbers:
a *= num
return a

pass
``````

## 回答 15

”’了解循环逻辑使用的唯一简单方法”’

”’the only simple method to understand the logic use for loop”’

Lap=[2,5,7,7,9] x=1 for i in Lap: x=i*x print(x)

## 回答 16

``````def myfunc(lst):
multi=1
for product in lst:
multi*=product
return product``````

It is very simple do not import anything. This is my code. This will define a function that multiplies all the items in a list and returns their product.

``````def myfunc(lst):
multi=1
for product in lst:
multi*=product
return product
``````