Python filter()- Funktion
Beispiel
Filtern Sie das Array und geben Sie ein neues Array zurück, das nur die Werte gleich oder größer als 18 enthält:
ages = [5, 12, 17, 18, 24, 32]
def myFunc(x):
if x < 18:
return False
else:
return True
adults
= filter(myFunc, ages)
for x in adults:
print(x)
Definition und Verwendung
Die filter()
Funktion gibt einen Iterator zurück, in dem die Elemente durch eine Funktion gefiltert werden, um zu testen, ob das Element akzeptiert wird oder nicht.
Syntax
filter(function, iterable)
Parameterwerte
Parameter | Description |
---|---|
function | A Function to be run for each item in the iterable |
iterable | The iterable to be filtered |