如何从“hh:mm”时间戳列表中获得最大值?

vot*_*ine 1 python list max python-3.x

我有一个时间字符串列表(音乐曲目长度),就像这样:

music_lengths = ['4:30', '4:59', '7:30', ...]
Run Code Online (Sandbox Code Playgroud)

如何找到该列表的最大值(最长轨道)?

Nic*_*ick 8

您可以time使用time.strptime这些值转换为对象并取最大值:

import time

music_lengths = ['4:30', '11:04', '4:59', '7:30', '1:23']
longest = max(music_lengths, key=lambda t:time.strptime(t, '%M:%S'))
print(longest)
Run Code Online (Sandbox Code Playgroud)

输出(对于我的示例数据)

11:04
Run Code Online (Sandbox Code Playgroud)