Funkce Python filter() .
Příklad
Filtrujte pole a vraťte nové pole pouze s hodnotami rovnými 18 nebo vyššími:
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)
Definice a použití
Funkce filter()
vrací iterátor, pokud jsou položky filtrovány funkcí, aby se otestovalo, zda je položka přijata nebo ne.
Syntax
filter(function, iterable)
Hodnoty parametrů
Parameter | Description |
---|---|
function | A Function to be run for each item in the iterable |
iterable | The iterable to be filtered |