The built-in function filter(function, iterable)
is defined as such in the language manual:
filter(function, iterable)
Build a iterator from the elements of everlasting for which
Function returns true. The everlasting can be a sequence, a container
that supports iteration, or an iterator. If Function is None, the function
identity will be used, that is, all elements of the everlasting that are false
are removed.
Note that filter(function, iteravel)
is equivalent to the generating expression:
(item for item in iteravel if function(item))
if Function is not None
.
(item for item in iteravel if item)
if Function is None
.
So when did filter(None, lista)
you informed the interpreter that you would like to get the generator (item for item in lista if item)
that reality does not filter the lista
only produces the generator that reiterates on its items.
To perform the filtering it is necessary to pass a comparative function, as argument in the first parameter. This should return a boolean where:
True
informs that the item will be accepted by the filter.
False
informs that the item will be rejected by the filter.
As a filter a anonymous function.
Example: In a list of 100 dictionaries {"ID":inteiro , "Name": string}
whose the IDs
range from 1 to 100, print only dictionaries whose ID <= 10
and that ID
be equal.
#Cria uma lista com dicionários cujo os ids vão de 1 até 100.
entrada =[{"ID": i + 1, "Name": f"Teste{i + 1}"} for i in range(100)]
#Cria o filtro que só retorna True se o ID de x for menor que 10 e a mesmo tempo o ID seja par.
filtro = lambda x: x["ID"] <= 10 and x["ID"] % 2 == 0
#Filtra a lista entrada.
filtrados = list(filter(filtro , entrada))
#Imprime o resultado.
print(filtrados)
This example will result in:
[{'ID': 2, 'Name': 'Teste2'},
{'ID': 4, 'Name': 'Teste4'},
{'ID': 6, 'Name': 'Teste6'},
{'ID': 8, 'Name': 'Teste8'},
{'ID': 10, 'Name': 'Teste10'}]
Returning to the example of the question where you want to perform an element filtering whose ID
is equal to 1:
entrada =[{"ID": i + 1, "Name": f"Teste{i + 1}"} for i in range(100)]
#Filtro para aceitar apenas o x cujo o ID é um.
filtro = lambda x: x["ID"] == 1
filtrados = list(filter(filtro , entrada))
print(filtrados)
What returns:
[{'ID': 1, 'Name': 'Teste1'}]
This answers your question? Filter elements from a Python list
– fernandosavio