Home > Back-end >  How to seperate list of hours:minutes:seconds in python?
How to seperate list of hours:minutes:seconds in python?

Time:01-07

Hello i would like to seperate a list that looks like this:

04:05:43.0
04:05:44.0
04:05:45.0
04:05:46.0
04:05:47.0
04:05:48.0
04:05:49.0
04:05:50.0
04:05:51.0
04:05:52.0
04:05:53.0
04:05:54.0
04:05:55.0
04:05:56.0
04:05:57.0
04:05:58.0
04:05:59.0
04:06:00.0
04:06:01.0
04:06:02.0
04:06:03.0
04:06:08.0

to 3 seperated lists with hours/minutes and seconds

Expected result:

hrs = [4, 4, 4, 4, 4, 4, ......]
mins = [5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6,.... ]
secs = [1, 2, 3, 4, 5, 6,.....]

CodePudding user response:

This code does exactly what you want!

list_ = [
    '04:05:43.0',
    '04:05:44.0',
    '04:05:45.0'
]

# create 3 different lists, seperating hrs mins and secs
hrs = []
mins = []
secs = []

# loop through the list and split the strings into 3 different lists
for i in list_:
    hrs.append(int(i.split(':')[0]))
    mins.append(int(i.split(':')[1]))
    secs.append(int(i.split(':')[2].split('.')[0]))

CodePudding user response:

You can use zip and str.split in a generator expression:

# the output will be tuples
hrs, mins, secs = zip(*((int(float(x)) for x in s.split(':')) for s in data))

Or for lists instead of tuples:

hrs, mins, secs = map(list, zip(*((int(float(x)) for x in s.split(':'))
                                  for s in data)))

Output:

# hrs
[4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4]

# mins
[5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6]

# secs
[43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 0, 1, 2, 3, 8]

CodePudding user response:

It's easy when data is in fixed format

lst = [
'04:05:43.0',
'04:05:44.0',
'04:05:45.0',
'04:05:46.0',
'04:05:47.0',
'04:05:48.0',
'04:05:49.0',
'04:05:50.0',
'04:05:51.0',
'04:05:52.0',
'04:05:53.0',
'04:05:54.0',
'04:05:55.0',
'04:05:56.0',
'04:05:57.0',
'04:05:58.0',
'04:05:59.0',
'04:06:00.0',
'04:06:01.0',
'04:06:02.0',
'04:06:03.0',
'04:06:08.0',
]
hrs  = [int(i[0:2]) for i in lst]
mins = [int(i[3:5]) for i in lst]
secs = [int(i[6:8]) for i in lst]
print( "hrs =", hrs)
print( "min =", mins)
print( "secs =", secs)

Output:

hrs= [4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4]
min= [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6]
secs= [43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 0, 1, 2, 3, 8]
  • Related