Falsche Werte in Python entfernen

PythonPythonBeginner
Jetzt üben

This tutorial is from open-source community. Access the source code

💡 Dieser Artikel wurde von AI-Assistenten übersetzt. Um die englische Version anzuzeigen, können Sie hier klicken

Einführung

In dieser Herausforderung musst du eine Python-Funktion schreiben, die falsche Werte aus einer Liste entfernt.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python(("Python")) -.-> python/PythonStandardLibraryGroup(["Python Standard Library"]) python/BasicConceptsGroup -.-> python/variables_data_types("Variables and Data Types") python/BasicConceptsGroup -.-> python/booleans("Booleans") python/BasicConceptsGroup -.-> python/comments("Comments") python/DataStructuresGroup -.-> python/lists("Lists") python/DataStructuresGroup -.-> python/tuples("Tuples") python/FunctionsGroup -.-> python/function_definition("Function Definition") python/FunctionsGroup -.-> python/build_in_functions("Build-in Functions") python/PythonStandardLibraryGroup -.-> python/data_collections("Data Collections") subgraph Lab Skills python/variables_data_types -.-> lab-13605{{"Falsche Werte in Python entfernen"}} python/booleans -.-> lab-13605{{"Falsche Werte in Python entfernen"}} python/comments -.-> lab-13605{{"Falsche Werte in Python entfernen"}} python/lists -.-> lab-13605{{"Falsche Werte in Python entfernen"}} python/tuples -.-> lab-13605{{"Falsche Werte in Python entfernen"}} python/function_definition -.-> lab-13605{{"Falsche Werte in Python entfernen"}} python/build_in_functions -.-> lab-13605{{"Falsche Werte in Python entfernen"}} python/data_collections -.-> lab-13605{{"Falsche Werte in Python entfernen"}} end

Kompakte Liste

Schreibe eine Funktion compact(lst), die eine Liste als Argument nimmt und eine neue Liste zurückgibt, aus der alle falschen Werte entfernt wurden. Falsche Werte umfassen False, None, 0 und "".

Um dieses Problem zu lösen, kannst du die filter()-Funktion verwenden, um falsche Werte aus der Liste zu filtern.

def compact(lst):
  return list(filter(None, lst))
compact([0, 1, False, 2, '', 3, 'a','s', 34]) ## [ 1, 2, 3, 'a','s', 34 ]

Zusammenfassung

In dieser Herausforderung hast du gelernt, wie du falsche Werte aus einer Liste mit der filter()-Funktion in Python entfernen kannst.