List Comprehension in Python

in Deutsch D-A-CH2 years ago

Das ist auch ein nützliches Feature in Python. Mit den List Comprehensions kann man alle Elemente einer Liste auf etwas prüfen oder modifizieren, um dann eine neue Liste zu erhalten. Dadurch lassen sich filter- oder auch mapfunktionen in einer Zeile schreiben.

Genauso wie für die Datenklassen folgt hier auch ein Beispiel für ein besseres Verständnis. Cooles Feature oder ;)

def list_comprehension(wordlist):
    # [expression for element in collection if something]
    return [elem.upper() for elem in wordlist if len(elem) >= 4]

def the_classic_way(wordlist):
    new_wordlist = []
    for elem in wordlist:
        if len(elem) >= 4:
            new_wordlist.append(elem.upper())
    return new_wordlist

if __name__ == '__main__':
    # this is the list to show the list comprehensions
    # first all words with a length lesser than 4 will be filtered
    # the rest words will be transformed to uppercase
    words = ['blurt','manfred','haus','info','set','get']

    # but first the classic way to see the differences
    print(the_classic_way(words))

    # now the new way
    print(list_comprehension(words))

Sort:  

Congratulations @ozelot47! You have completed the following achievement on the Hive blockchain and have been rewarded with new badge(s):

You got more than 2500 replies.
Your next target is to reach 2750 replies.

You can view your badges on your board and compare yourself to others in the Ranking
If you no longer want to receive notifications, reply to this comment with the word STOP