Die Funktion »map« in Python
Funktion auf alle Einträge einer Liste anwenden
Das zweite Argument von »map« muß ein iterables Objekt sein.
Das Ergebnis von »map« ist ein Iterator.
- Auswertung
iterator = map( lambda x: x*2, [ 52, 1, 19 ])
next( iterator )
104
next( iterator )
2
next( iterator )
38
Während die Verwendung einer lambda-Bindung in Python als schlechter Stil gilt, gilt die Verwendung eines lambda-Ausdrucks (wie oben) nicht als schlechter Stil.
- Auswertung
def f( x ):
return 2*xiterator = map( f, [ 52, 1, 19 ])
next( iterator )
104
next( iterator )
2
next( iterator )
38
Das aufrufbare Objekt »list« kann jedoch aus jedem Iterator eine Liste machen.
- Auswertung
list( map( f, [ 52, 1, 19 ]))
[104, 2, 38]
- Auswertung
list( map( lambda x: x+2, [ 52, 1, 19 ]))
[54, 3, 21]
- Protokoll
from operator import neg
list( map( neg, range( 0, 5 )))
[0, -1, -2, -3, -4]
Schlecht wäre ein unnötiges Lambda, wie im folgenden Beispiel:
- Protokoll
from operator import neg
list( map( lambda x: neg( x ), range( 0, 5 )))
[0, -1, -2, -3, -4]
- Protokoll (vereinfacht)
>>> help(map)
class map(object)
| iterator = map(func, iterable)
| Make an iterator that computes the function using arguments from
| each the iterable. Stops when the iterable is exhausted.- Protokoll
list( map( len,( 'ab', 'cdefgh', 'i', 'jk' )))
[2, 6, 1, 2]
- Protokoll
list( map( chr, range( 65, 65 + 6 )))
['A', 'B', 'C', 'D', 'E', 'F']
- Protokoll
print( ', '.join( map( chr, range( 65, 65 + 6 ))))
A, B, C, D, E, F
- Protokoll
''.join( map( lambda x: chr( ( ord( x )-ord( 'a' )+ 13 )%26 + ord( 'a' )), 'abc' ))
'nop'
Die Rot13 -Kodierung ist involutorisch.
- Protokoll
''.join( map( lambda x: chr( ( ord( x )-ord( 'a' )+ 13 )%26 + ord( 'a' )), 'nop' ))
'abc'
- Protokoll
for i in map( neg, range( 0, 5 )): print( i )
0
-1
-2
-3
-4print( *map( lambda x: x**2, range( 1, 5 )))
1 4 9 16
- Protokoll
f = lambda x: 'Null' if x == 0 else 'Eins' if x == 1 else 'Zwei'
list( map( f, [ 0, 1, 2 ]))
['Null', 'Eins', 'Zwei']
Während die Verwendung einer lambda-Bindung in Python als schlechter Stil gilt, gilt die Verwendung eines lambda-Ausdrucks (wie oben) nicht als schlechter Stil.
Übungsaufgaben
/ Übungsaufgabe
Der folgende Ausdruck zeigt die Herstellung einer Rot13 -Kodierung von »abc«.
- Protokoll
''.join( map( lambda x: chr( ( ord( x )-ord( 'a' )+ 13 )%26 + ord( 'a' )), 'abc' ))
'nop'
Schreiben Sie einen Ausdruck, der eine Zeichenfolge aus 10 zufälligen kleinen Buchstaben erzeugt.