-1

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?

2 Answers2

1

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'
Sash Sinha
  • 18,743
  • 3
  • 23
  • 40
user3435121
  • 633
  • 4
  • 13
1

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']
Andreas
  • 159
  • 1
  • 7