Вот 8 способов перемножить все числа в списке Python.
Содержание
Способ 1: использование обхода
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
def multiplyList(mainList): output = 1 for x in mainList: output = output * x return output list1 = [11, 21, 19] list2 = [18, 21, 46] print(multiplyList(list1)) print(multiplyList(list2)) |
Выход
|
1 2 |
4389 17388 |
Способ 2: применение метода numpy.prod()
|
1 2 3 4 5 6 7 8 9 10 |
import numpy as np list1 = [11, 21, 19] list2 = [18, 21, 46] output1 = np.prod(list1) output2 = np.prod(list2) print(output1) print(output2) |
Выход
|
1 2 |
4389 17388 |
Способ 3: лямбда-функция
|
1 2 3 4 5 6 7 8 9 10 |
from functools import reduce list1 = [11, 21, 19] list2 = [18, 21, 46] output1 = reduce((lambda x, y: x * y), list1) output2 = reduce((lambda x, y: x * y), list2) print(output1) print(output2) |
Выход
|
1 2 |
4389 17388 |
Способ 4: метод math.prod()
|
1 2 3 4 5 6 7 8 9 10 |
import math list1 = [11, 21, 19] list2 = [18, 21, 46] output1 = math.prod(list1) output2 = math.prod(list2) print(output1) print(output2) |
Выход
|
1 2 |
4389 17388 |
Способ 5: функция mul() модуля оператора
|
1 2 3 4 5 6 7 8 |
from operator import * list1 = [11, 21, 19] n = 1 for i in list1: n = mul(i, n) print(n) |
Выход
|
1 |
4389 |
Способ 6: использование обхода по индексу
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
def multiplyList(mainList): result = 1 for i in range(0, len(mainList)): result = result * mainList[i] return result list1 = [11, 21, 19] list2 = [18, 21, 46] print(multiplyList(list1)) print(multiplyList(list2)) |
Выход
|
1 2 |
4389 17388 |
Способ 7: использование itertools.accumulate()
|
1 2 3 4 5 6 7 8 9 10 |
from itertools import accumulate list1 = [11, 21, 19] list2 = [18, 21, 46] output1 = list(accumulate(list1,(lambda x, y: x * y))) output2 = list(accumulate(list2,(lambda x, y: x * y))) print(output1[-1]) print(output2[-1]) |
Выход
|
1 2 |
4389 17388 |
Способ 8: применение рекурсивной функции
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
def product_recursive(numbers): if not numbers: return 1 return numbers[0] * product_recursive(numbers[1:]) list1 = [11, 21, 19] product1 = product_recursive(list1) print(product1) list2 = [18, 21, 46] product2 = product_recursive(list2) print(product2) |
Выход
|
1 2 |
4389 17388 |
