Reputation: 1281
We have the following code
hour_selections = [(str(t), "%02d:00" % t) for t in range(10)]
that produces
[('0', '00:00'), ('1', '01:00'), ('2', '02:00'), ('3', '03:00'), ... ('9', '09:00') ]
what is an easy way to create the following?
[
('0:00', '00:00'), ('0:15', '00:15'), ('0:30', '00:30'), ('0:45', '00:45'),
('1:00', '01:00'), ('1:15', '01:15'), ('1:30', '01:30'), ('1:45', '01:45'),
....
('10:00', '10:00'), ('10:15', '10:15'), ('10:30', '10:30'), ('10:45', '10:45')
]
for use in a time selection dropdown list?
Upvotes: 1
Views: 323
Reputation: 1124558
Use nested loops:
[('{}:{:02}'.format(h, q), '{:02}:{:02}'.format(h, q)) for h in range(11) for q in (0, 15, 30, 45)]
List comprehensions work just like nested for loops; if you can work out the sequence as a series of nested loop, you can put it in a list comp:
res = []
for hour in range(11):
for quarter in (0, 15, 30, 45):
res.append(('{}:{:02}'.format(hour, quarter), '{:02}:{:02}'.format(hour, quarter)))
Demo:
>>> [('{}:{:02}'.format(h, q), '{:02}:{:02}'.format(h, q)) for h in range(11) for q in (0, 15, 30, 45)]
[('0:00', '00:00'), ('0:15', '00:15'), ('0:30', '00:30'), ('0:45', '00:45'), ('1:00', '01:00'), ('1:15', '01:15'), ('1:30', '01:30'), ('1:45', '01:45'), ('2:00', '02:00'), ('2:15', '02:15'), ('2:30', '02:30'), ('2:45', '02:45'), ('3:00', '03:00'), ('3:15', '03:15'), ('3:30', '03:30'), ('3:45', '03:45'), ('4:00', '04:00'), ('4:15', '04:15'), ('4:30', '04:30'), ('4:45', '04:45'), ('5:00', '05:00'), ('5:15', '05:15'), ('5:30', '05:30'), ('5:45', '05:45'), ('6:00', '06:00'), ('6:15', '06:15'), ('6:30', '06:30'), ('6:45', '06:45'), ('7:00', '07:00'), ('7:15', '07:15'), ('7:30', '07:30'), ('7:45', '07:45'), ('8:00', '08:00'), ('8:15', '08:15'), ('8:30', '08:30'), ('8:45', '08:45'), ('9:00', '09:00'), ('9:15', '09:15'), ('9:30', '09:30'), ('9:45', '09:45'), ('10:00', '10:00'), ('10:15', '10:15'), ('10:30', '10:30'), ('10:45', '10:45')]
Upvotes: 2