CKTIS / Python
functools.reduce
Przetwarza elementy od lewej, wywołując funkcję z akumulatorem i następnym elementem.
Wersja: Python 3.14; repository image, production runtime not attested
Składnia
functools.reduce(function, iterable, /)
functools.reduce(function, iterable, /, initial)Przetwarza elementy od lewej, wywołując funkcję z akumulatorem i następnym elementem.
Bez initial zaczyna od pierwszego elementu, pojedynczy zwraca bez wywołania funkcji, a pusty zbiór wejściowy zgłasza TypeError. W 3.14 initial można podać po nazwie.
(10-3)-2 daje 5, a puste wejście z initial=10 daje 10.
from functools import reduce
from operator import sub
assert reduce(sub, [3, 2], initial=10) == 5
assert reduce(sub, [7]) == 7 and reduce(sub, [], initial=10) == 10
try:
reduce(sub, [])
except TypeError:
pass
else:
raise AssertionError
Przykłady
import functools
from operator import sub
print(functools.reduce(sub, [3, 2], 10))
print(functools.reduce(sub, [], 10))
Wynik
5 10
(10-3)-2 daje 5, a puste wejście z initial=10 daje 10.