The ratio of None
is because the map
function performs its functions for each element of the list, so a return on those functions is always necessary. Since you do not return anything in else
(which does not exist in your functions), Python assumes None
in these cases.
If you are required to use map
, a possible solution is to simply remove the None
after calling map
, perhaps using a understanding :
lista = [0,1,2,3,4,5,6,7,8,9,10]
def par(numero):
if numero % 2 == 0:
return numero
def impar(numero):
if numero % 2 != 0:
return numero
par = [i for i in list(map(par,lista)) if i is not None]
impar = [i for i in list(map(impar,lista)) if i is not None]
print(par)
print(impar)
Note that by doing par = ...
you change your par
previously defined so that it can no longer be used.
It might be nice to use another variable name. :)
If on the other hand you do not need to use map
, do it directly:
lista = [0,1,2,3,4,5,6,7,8,9,10]
par = [i for i in lista if i % 2 == 0]
impar = [i for i in lista if i % 2 != 0]
print(par)
print(impar)
There is yet another option. If you are using NumPy , you can do this:
import numpy as np
lista = np.array([0,1,2,3,4,5,6,7,8,9,10])
paridx = np.logical_not((lista % 2).astype(bool))
imparidx = (lista % 2).astype(bool)
par = lista[paridx]
impar = lista[imparidx]
print(par)
print(impar)
Explaining:
The command lista % 2
returns a list with the remainders of the division of each element by 2, which for its list it will return [0 1 0 1 0 1 0 1 0 1 0]
.
The (lista % 2).astype(bool)
command simply converts these 0s and 1s to logical values, making this list become [False True False True False True False True False True False]
. Notice how basically it indicates False
where the remainder of the division by 2 is zero, and True
where the rest of the division by 2 is 1. That is, basically it indicates true where the number in that position (index) is odd.
This is why the final command is (lista % 2).astype(bool)
to indicate the indexes of odd numbers and np.logical_not((lista % 2).astype(bool))
(the logical negation of those values) to indicate the indices of even numbers.
Finally, these indexes are used directly to "filter" in the original list the items where the index indicates true ( True
) - a very useful and useful feature when manipulating data: par = lista[paridx]
and impar = lista[imparidx]