创建仅30分钟的音乐播放列表

2024-09-30 14:24:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一名吉他手,他想为自己创建一个歌曲播放列表,播放我所知道的所有歌曲。我现在认识一对,我只想玩30分钟

为此,我的想法是创建一个带有歌曲标题和歌曲持续时间的词典。 我想随机选择一首歌,持续时间不超过30分钟

我的问题是如何写下一首歌的分秒

我的想法是:

Playlist = {"Before I Forget": 4.21, "Unsainted":4.20.....}

但它将信息存储为一个浮点数

有什么建议吗


Tags: 信息标题歌曲播放列表playlist建议词典持续时间
1条回答
网友
1楼 · 发布于 2024-09-30 14:24:25

有几种不同的方法可以做到这一点。有一个最佳的解决方案,让你尽可能接近你的目标,但你希望播放列表是随机的,一切最终得到播放,所以像这样的事情应该做的工作

from random import randint, shuffle

# create some tracks between 2-4 minutes for testing
tracks = { "Track {0}".format(i): "{0}:{1:02d}".format(randint(2, 3), randint(0, 59)) for i in range(20) }
print(tracks)

# covert to a list of elements with the time in seconds
def min_to_sec(x):
    m, s = x.split(":")
    return int(m) * 60 + int(s)
items = [ (k, min_to_sec(v)) for k, v in tracks.items() ]

# randomise
shuffle(items)

# a function that sums the lengths from an index position till
# it exceeds the max.
def select_tracks(items, index, max_seconds):
    total = 0
    selected = []
    for name, length in items[index:]:
        if total + length > max_seconds:
            break
        total += length
        selected.append(name)

    return total, selected


# run at each start position
results = [ select_tracks(items, i, 30*60) for i in range(len(items)) ]

# if we sort and select the last that is the best for this randomised order
results.sort()
playlist = results[-1]

print("\nPlaylist: {0} ({1} seconds)".format(", ".join(playlist[1]), playlist[0]))

输出:

{'Track 0': '2:51', 'Track 1': '2:25', 'Track 2': '3:21', 'Track 3': '3:03', 'Track 4': '3:22', 'Track 5': '3:03', 'Track 6': '3:32', 'Track 7': '3:58', 'Track 8': '3:40', 'Track 9': '2:16', 'Track 10': '3:32', 'Track 11': '3:52', 'Track 12': '3:03', 'Track 13': '2:37', 'Track 14': '2:45', 'Track 15': '2:57', 'Track 16': '3:19', 'Track 17': '3:06', 'Track 18': '2:15', 'Track 19': '3:05'}

Playlist: Track 5, Track 14, Track 18, Track 9, Track 8, Track 17, Track 10, Track 19, Track 2, Track 0 (1794 seconds)

相关问题 更多 >