简体   繁体   中英

Python (Django) Remove Items From Choice List

I have a list of times for my web form and I need to remove some choices from the list based on minimum and maximum minute value.

For example I want to only display times between 60 and 180 minutes

Django Form:

time_list = (
        ('', 'Select'),
        ('15', '15 Minutes'),
        ('30', '30 Minutes'),
        ('45', '45 Minutes'),
        ('60', '60 Minutes'),
        ('75', '1:15'),
        ('90', '1:30'),
        ('105', '1:45'),
        ('120', '2:00'),
        ('135', '2:15'),
        ('150', '2:30'),
        ('165', '2:45'),
        ('180', '3:00'),
        ('240', '4:00'),
        ('300', '5:00'),
        ('360', '6:00'),
        ('420', '7:00'),
        ('480', '8:00'),
        ('540', '9:00'),
        ('600', '10:00'),
        ('660', '11:00'),
        ('720', '12:00'),
        ('1440', '24:00'),
    ) 

min_time = 60 #defined in DB
max_time = 180 #defined in DB

Here I'm unsuccessfully trying to filter the list:

tmp = []
    for i in time_list:
        if i > min_time and i < max_time:
            tmp.append(i)
time_list =  tmp

Try to change it to

time_list = iter(time_list)
next(time_list)
tmp = []
    for i in time_list:
        if int(i[0]) > min_time and int(i[0]) < max_time:
            tmp.append(i)
time_list =  tmp

In one line:

time_list = list(filter(lambda x: min_time < int(x[0]) < max_time, time_list[1:]))

If you want to include the empty choice:

time_list = [time_list[0]] + list(filter(lambda x: min_time < int(x[0]) < max_time, time_list[1:]))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM