CKTIS / Python
functools.reduce
Združuje elemente z leve s klicanjem funkcije z akumulatorjem in naslednjim elementom.
Različica: Python 3.14; repository image, production runtime not attested
Sintaksa
functools.reduce(function, iterable, /)
functools.reduce(function, iterable, /, initial)Združuje elemente z leve s klicanjem funkcije z akumulatorjem in naslednjim elementom.
Brez initial začne s prvim, enega vrne nespremenjenega in prazen vhod sproži TypeError. V 3.14 se initial lahko poda po imenu.
(10-3)-2 da 5 in prazen vhod z initial=10 da 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
Primeri
import functools
from operator import sub
print(functools.reduce(sub, [3, 2], 10))
print(functools.reduce(sub, [], 10))
Rezultat
5 10
(10-3)-2 da 5 in prazen vhod z initial=10 da 10.