繁体   English   中英

我如何比较歌曲时间的长度?

[英]How I can compare the length of song time?

我需要比较歌曲的长度 tme 来找出我的播放列表中哪首歌最长并打印他的名字。 我得到了所有时间的列表,例如我得到了列表['5:13', '4:05', '4:15', '4:23', '4:13']现在我需要比较时间,但我不知道如何将 str 列表转换为 int 列表并比较时间。 有什么建议吗?

max()提供了一种使用键 function 转换列表中每个项目的方法。

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'

短而无痛:

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']

使用datetime模块将表示持续时间的字符串转换为 datetime 对象并进行比较。 因为你没有提到你是如何存储歌曲名称的,所以我认为他们的索引要显示。

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')}")

output 将是:

index 0 is the longest which has a duration of 05:13

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM