Question

I currently have a list of strings in the format (mm:ss.ddd):

[['0:00.762', '0:01.435'], ['2:01.374', '2:07.423'], ['3:01.412', '3:07.314']]

That I'd like to convert to strings in the format (ss.ddd):

[['0.762', '1.435'], ['121.374', '127.423'], ['181.412', '187.314']]

Essentially taking the characters to the left of the delimiter ':', converting to an integer, multiplying by 60, and adding it to the numbers to the right of ':' but before '.'

I am very unfamiliar with Python's string manipulation tools and was wondering if anyone can think of a clever and efficient way to do this using built in methods.

Thanks for all help

Was it helpful?

Solution

Let's break the problem down into parts. First, we need a function that can convert each element from the mm:ss.dd format to ss.dd. That's pretty easy to do:

def convert(s):
    mins, secs = s.split(':')
    mins = int(mins)
    secs = float(secs)
    secs = 60 * mins + secs
    return secs

It seems we can just use map to convert the elements of the list:

converted_times = map(convert, orig_times)

However, convert takes a single element (e.g., '0:00.762'), whereas the data is actually a list of lists -- specifically, a list of pairs. We need another function that accepts a pair of elements (as a list) and returns them. We also want to return them as a string rather than a float:

def convert_pair(p):
    p0, p1 = convert(p[0]), convert(p[1])
    return [str(p0), str(p1)]

Putting this together, we can simply do

converted_times = map(convert_pair, orig_times)

to transform the list of data pairs.

A sample of this code can be found here.

OTHER TIPS

from decimal import Decimal

times = [['0:00.762', '0:01.435'], ['2:01.374', '2:07.423'], ['3:01.412', '3:07.314']]

converted_times = [ [str(int(time.split(":")[0])*60 + Decimal(time.split(":")[1])) for time in time_list] for time_list in times]
# thanks @shaktimaan

But why are you doing this with string methods? Here's a better way:

import datetime

times = [['0:00.762', '0:01.435'], ['2:01.374', '2:07.423'], ['3:01.412', '3:07.314']]

def convert_time(times):
    for timepair in times:
        accumulator = list()
        for time in timepair:
            t = datetime.datetime.strptime(time,"%M:%S.%f")
            accumulator.append("{}.{}".format(t.minute*60+t.second,t.microsecond//1000))
        yield accumulator

for timepair in convert_time(times):
    print(timepair) # or whatever.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top