Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Condensing Multiple List Comprehensions

I have a list with input in this form:

open_info = ['Cube 1, 9:30am to 10:00am, Thursday, March 3, 2016', 'Cube 2, 5:00pm to 5:30pm, Thursday, March 3, 2016']

I want to parse through this information to create a new list in this form:

open_times = [[9, 30, 'am'],[5, 0, 'pm']]

With the hour at first index, minutes at second, and am/pm at the third index. I am only recording the first time value for each list element, because the intervals I am dealing with are always 30 minutes long.

I have accomplished this by using the following python list comprehensions:

open_times = [x.split(",")[1].replace(" ","").split("to") for x in open_info]
open_times = [x[0].split(":")+x[1].split(":") for x in open_times]
open_times = [[int(x[0]),int(x[1][:2]),x[1][2:]] for x in open_times]

I was wondering if there was to create a nested list comprehension out of all of these. I've looked at the python documentation and read some blogs on the subject but I'm still having trouble accomplishing this.

like image 364
Bryce Morrow Avatar asked Mar 14 '23 01:03

Bryce Morrow


2 Answers

To answer the question of how to 'nest' list comprehensions, you might do this to combine lines 1 and 2....

open_times = [y[0].split(":")+y[1].split(":") for y in [x.split(",")[1].replace(" ","").split("to") for x in open_info]]

... but this is really messy. The 3 lines are more understandable and cleaner here. You might also think about writing this as a series of loops since there's a lot going on inside the comprehension that would be cleaner outside of one.

like image 40
dfb Avatar answered Mar 20 '23 17:03

dfb


You could use the following:

open_info = ['Cube 1, 9:30am to 10:00am, Thursday, March 3, 2016', 'Cube 2, 5:00pm to 5:30pm, Thursday, March 3, 2016']

answer = [[int(s.split(':',1)[0][-2:]), int(s.split(':')[1][:2]), 
           s.split(':')[1][2:4]] for s in open_info]
print(answer)

Output

[[9, 30, 'am'], [5, 0, 'pm']]

In these circumstances, however, it may be more readable to use map instead of a list comprehension:

def func(s):
    hour = int(s.split(':')[0][-2:])
    minute = int(s.split(':')[1][:2])
    suffix = s.split(':')[1][2:4]
    return [hour, minute, suffix]

answer = map(func, open_info)
print(answer)

Output

[[9, 30, 'am'], [5, 0, 'pm']]
like image 123
gtlambert Avatar answered Mar 20 '23 18:03

gtlambert