I need to compare the length of song tme to find what song in my play list is the longest and print his name. I got a list with all the times, for example I got the list ['5:13', '4:05', '4:15', '4:23', '4:13']
and now I need to compare the times but I have no idea how to convert the str list to int list and compare the times. Any suggetions?
CodePudding user response:
use the datetime
module to convert the strings representing the durations to datetime objects and compare them. since you have not mentioned how you store the song names I consider their indexes to show.
from datetime import datetime
durations = ['5:13', '4:05', '4:15', '4:23', '4:13']
dt_durations = [datetime.strptime(duration, '%M:%S') for duration in durations]
max_duration = max(dt_durations, key=lambda x: (x - datetime.min).total_seconds())
print(f"index {dt_durations.index(max_duration)} is the longest which has a duration of {max_duration.strftime('%M:%S')}")
the output would be:
index 0 is the longest which has a duration of 05:13
CodePudding user response:
max()
provides a way to use a key function to convert each item in the list.
def seconds(x):
m, s = x.split(':')
return int(m) * 60 int(s)
durations = ['5:13', '4:05', '4:15', '4:23', '4:13']
m = max(durations, key=seconds)
print(m) # will print '5:13'
CodePudding user response:
Short and painless:
durations=['5:13', '4:05', '4:15', '4:23', '4:13', '11:05']
print(sorted(durations, key=lambda x: tuple(map(int, x.split(":")))))
Output
['4:05', '4:13', '4:15', '4:23', '5:13', '11:05']