Reduzieren Iterabler mit Python
Eine Reduktion erlaubt es, mehrere Werte mit einer zweistelligen Funktion zu einem Wert zusammenzufassen.
- Ein Beispiel zur Anwendung von »reduce«
from functools import reduce
from operator import add
reduce( add, ( 1, 2, 3 ))
6
- Konsolenprotokoll
from functools import reduce
reduce( lambda x, y: x + ',' + y, 'ab' )
'a,b'
- Konsolenprotokoll
from functools import reduce
reduce( lambda x, y: x + ',' + y, 'abc' )
'a,b,c'
- Konsolenprotokoll
from functools import reduce
reduce( lambda x, y: x + ',' + y, 'a' )
'a'
- Konsolenprotokoll
from functools import reduce
reduce( lambda x, y: x + ',' + y, '' )
TypeError: reduce() of empty sequence with no initial value
- Konsolenprotokoll
from functools import reduce
reduce( lambda x, y: x + ',' + y, 'abcdef' )
'a,b,c,d,e,f'
- Konsolenprotokoll
from functools import reduce
reduce( lambda x, y: x + y, range( 3 ))
3
reduce( lambda x, y: x + y, range( 5 ))
10
- Konsolenprotokoll
from functools import reduce
from operator import add
reduce( add, range( 3 ))
3
reduce( add, range( 5 ))
10
- Weiteres Beispiel *
from functools import reduce
reduce( lambda x, y: '(' + x + ',' + y +')', 'abc' )
'((a,b),c)'
reduce( lambda x, y: '(' + x + ',' + y +')', 'abcdef' )
'(((((a,b),c),d),e),f)'
Übungsaufgaben
/ Übungsaufgabe
Berechnen Sie das Produkt aller natürlichen Zahlen von 1 (einschließlich) bis 5 (einschließlich), indem Sie »reduce« mit »mul« (Multiplikation) aus dem Modul »operator« und einem geeigneten range-Aufruf aufrufen. Das Ergebnis sollte «120» lauten.