[英]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(":")))))
['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.