English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
O método filter() constrói um iterador a partir dos elementos do objeto iterável, e a função retorna true.
Em resumo, o método filter() filtra o iterável dado com a ajuda de uma função, que testa se cada elemento do iterável é verdadeiro.
A sintaxe do método filter() é:
filter(função, iterável)
O método filter() aceita dois parâmetros:
função-
Função de teste do elemento do iterável que retorna true ou false, se None, a função padrão é a função de identidade-Se qualquer elemento for false, retorna false
iterável-O iterável a ser filtrado pode serconjuntos,listas,tuplasou qualquer contêiner de iteradores
O método filter() retorna um iterador, que passa a função de verificação para cada elemento do iterável.
O método filter() é equivalente a:
# Quando a função é definida (elemento for elemento in iterável if função(elemento)) # Quando a função é vazia (elemento for elemento in iterável if elemento)
# Lista ordenada alfabeticamente alphabets = ['a', 'b', 'd', 'e', 'i', 'j', 'o'] # Função para filtrar vogais def filterVowels(alphabet): vowels = ['a', 'e', 'i', 'o', 'u'] if(alphabet in vowels): return True else: return False filteredVowels = filter(filterVowels, alphabets) print('Os vocáis filtrados são:') para vovela em filteredVowels: print(vowel)
When running the program, the output is:
The filtered vowels are: a e i o
Here, we list a list of letters, and we just need to filter out the vowels from it.
We can use a for loop to traversealphabetsEach element in the list, and store it in another list, but in Python, using the filter() method can make this process easier and faster.
We have a filterVowels function that checks if a letter is a vowel. This function is passed along with the list of letters to the filter() method.
Then, the filter() method passes each letter to the filterVowels() method to check if it returns true. Finally, it creates an iterator that returns true (vowels).
Since the iterator itself does not store values, we traverse it and print out the vowels one by one.
# Random list randomList = [1, 'a', 0, False, True, '0'] filteredList = filter(None, randomList) print('Filtered elements are:') for element in filteredList: print(element)
When running the program, the output is:
The filtered elements are: 1 a True 0
Here,randomListis a random list composed of numbers, strings, and boolean values.
We willrandomListThe first parameter passed to filter() (filter function) isNone's methods.
When setting the filter function to None, the function defaults to the Identity function and checksin randomListwhether each element is true.
when we traverse the finalwhen filteringListThe elements we get are true: (1As 'w', '0', True and '0' are strings, so '0' is also true).