[英]How I can compare the length of song time?
I need to compare the length of song tme to find what song in my play list is the longest and print his name.我需要比较歌曲的长度 tme 来找出我的播放列表中哪首歌最长并打印他的名字。 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.我得到了所有时间的列表,例如我得到了列表
['5:13', '4:05', '4:15', '4:23', '4:13']
现在我需要比较时间,但我不知道如何将 str 列表转换为 int 列表并比较时间。 Any suggetions?有什么建议吗?
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(":")))))
['4:05', '4:13', '4:15', '4:23', '5:13', '11:05']
use the datetime
module to convert the strings representing the durations to datetime objects and compare them.使用
datetime
模块将表示持续时间的字符串转换为 datetime 对象并进行比较。 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: output 将是:
index 0 is the longest which has a duration of 05:13
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.