CKTIS / Python
functools.reduce
Faltet von links durch Aufruf der Funktion mit Akkumulator und nächstem Element.
Version: Python 3.14; repository image, production runtime not attested
Syntax
functools.reduce(function, iterable, /)
functools.reduce(function, iterable, /, initial)Faltet von links durch Aufruf der Funktion mit Akkumulator und nächstem Element.
Ohne initial startet das erste Element, ein einzelnes wird unverändert geliefert und leere Eingabe löst TypeError aus. In 3.14 ist initial als Schlüsselwort möglich.
(10-3)-2 ergibt 5 und leere Eingabe mit initial=10 ergibt 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
Beispiele
import functools
from operator import sub
print(functools.reduce(sub, [3, 2], 10))
print(functools.reduce(sub, [], 10))
Ergebnis
5 10
(10-3)-2 ergibt 5 und leere Eingabe mit initial=10 ergibt 10.