목록의 모든 항목을 파이썬과 함께 곱할 수 있습니까?
숫자 목록 을 가져 와서 곱하는 함수를 작성 해야합니다. 예 : [1,2,3,4,5,6]
나에게 줄 것이다 1*2*3*4*5*6
. 정말 당신의 도움을 사용할 수 있습니다.
파이썬 3 : 사용 functools.reduce
:
>>> from functools import reduce
>>> reduce(lambda x, y: x*y, [1,2,3,4,5,6])
720
파이썬 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
설명에 대한 문서화.
import functools
파이썬 3 이상 에서 라인 이 필요합니다 .
나는를 사용하는 것이 numpy.prod
작업을 수행 할 수 있습니다. 아래를 참조하십시오.
import numpy as np
mylist = [1, 2, 3, 4, 5, 6]
result = np.prod(np.array(mylist))
가져 오기를 피하고 더 복잡한 파이썬 영역을 피하려면 간단한 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
나는 일반 목록의 모든 요소를 함께 곱하는 함수에 대해 개인적으로 이것을 좋아합니다.
def multiply(n):
total = 1
for i in range(0, len(n)):
total *= n[i]
print total
컴팩트하고 간단한 것 (변수 및 for 루프)을 사용하며 직관적입니다. (문제를 생각하고, 하나만 취하고, 곱한 다음 다음에 곱하는 등의 방식으로 보입니다.) )
내 기계의 성능 측정 결과는 다음과 같습니다. 장기 실행 루프에서 작은 입력에 대해 수행되는 경우와 관련이 있습니다.
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의 오버플로에주의하십시오.
간단한 방법은 다음과 같습니다.
import numpy as np
np.exp(np.log(your_array).sum())
시작 Python 3.8
하여 prod
함수가 math
표준 라이브러리 의 모듈에 포함되었습니다 .
math.prod (iterable, *, start = 1)
start
iterable 숫자 의 값 (기본값 : 1) 곱의 곱을 반환합니다 .
import math
math.prod([1, 2, 3, 4, 5, 6]) # 720
Note that if the iterable is empty, this will produce 1
(or the start
value if provided).
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))
nums = str(tuple([1,2,3]))
mul_nums = nums.replace(',','*')
print(eval(mul_nums))
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
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)
My solution:
def multiply(numbers):
a = 1
for num in numbers:
a *= num
return a
pass
Numpy has the prod function that returns the product of a list, or in this case since its numpy, its technically the product of an array over a given axis.
one way:
import numpy
a = [1,2,3,4,5,6]
b = numpy.prod(a)
the other just plays at how you import:
from numpy import prod
a = [1,2,3,4,5,6]
b = prod(a)
How about using recursion?
def multiply(lst):
if len(lst) > 1:
return multiply(lst[:-1])* lst[-1]
else:
return lst[0]
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
'IT' 카테고리의 다른 글
Spring의 GA, RC 및 M2 릴리스의 차이점은 무엇입니까? (0) | 2020.05.19 |
---|---|
Android : 태블릿에 세로 및 가로를 허용하지만 휴대 전화에서 세로를 강제로 설정 하시겠습니까? (0) | 2020.05.19 |
open with 문을 사용하여 파일을 여는 방법 (0) | 2020.05.17 |
C ++ 구조체의 멤버는 기본적으로 0으로 초기화됩니까? (0) | 2020.05.17 |
프로그래밍 방식으로 속성을 어떻게 설정합니까? (0) | 2020.05.17 |