How to use the filter function using lists?

Asked

Viewed 65 times

1

I am trying to filter the months with only 31 days, however mdays is a list and I need to compare with an integer value. Taking the Dice, it becomes an integer value, but then I don’t know how to use it since I can only compare one month with the number of days (31). In the exercise, specifically, the teacher requests the use of the functions map, filter and reduce.

from calendar import mdays, month_name
   from functools import reduce


#Listar todos os meses do ano com 31 dias

apenas_31 = list(filter(lambda i: i[mdays[i]] > 30, mdays))

2 answers

0

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))

0

Use filter and lambda will be more complicated than necessary here.

I recommend using a list comprehension, which is more readable, together with the function enumerate, iterates on the elements of a sequence together with its indices:

from calendar import mdays, month_name

apenas_31 = [month_name[i] for i, n in enumerate(mdays) if n > 30]
print(apenas_31)

output:

['January', 'March', 'May', 'July', 'August', 'October', 'December']
  • Thanks! The exercise specifically asked to use the filter function, but really list comprehension is much better!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.