As the jfaccioni reply, the use of list comprehension is most recommended as it is more readable. However, for teaching purposes, I will demonstrate how a possible solution would be using only map
and filter
.
Since the function filter(function, iterable)
returns only the elements of iterable
where the function
returns true, we can use it to filter the index of months that has 31 days:
indice_meses_31d = filter(lambda i: mdays[i]==31, range(1,13))
and map(function, iterable, ...)
apply the function function
to each element of iterable
, therefore:
nome_meses_31d = map(lambda i: month_name[i], indice_meses_31d)
Uniting the two functions in a single row:
nome_meses_31d = map(lambda i: month_name[i], filter(lambda i: mdays[i]=31, range(1,13)))
Use print(list(nome_meses_31d))
to display the name of the months with 31 days.
Complete Code:
from calendar import mdays, month_name
indice_meses_31d = filter(lambda i: mdays[i]==31, range(1,13))
nome_meses_31d = map(lambda i: month_name[i], indice_meses_31d)
print(list(nome_meses_31d))
or
from calendar import mdays, month_name
nome_meses_31d = map(lambda i: month_name[i], filter(lambda i: mdays[i]==31, range(1,13)))
print(list(nome_meses_31d))
Thanks! The exercise specifically asked to use the filter function, but really list comprehension is much better!
– Juliana