如何随机打乱列表并按每5个为一组分批输出,实现歌单分批展示功能
问题说明
原有代码的核心问题如下:
- 缺失随机打乱歌单的逻辑
- 字符串相等判断的
or用法错误,== "Top Hits" or "top hits"的写法永远返回真值,无法正确匹配用户输入 - 没有按批次输出歌曲、循环询问用户的流程逻辑,询问时机也不符合需求
- 输出逻辑未做分页控制,会一次性打印所有歌曲
修正后完整代码
import random video_id_to_title = { 5390161: "Who Want Smoke", 7736243: "INDUSTRY BABY", 8267507: "STAY", 1012930: "Style", 1109274: "bad guy", 2981023: "Blank Space", 4922599: "Love Nwantiti Remix", 4559658: "Essence (Official Video)", 9897626: "Pepas", 5610524: "Outside (Better Days)", 6980497: "Lo Siento BB:/", 4547223: "Face Off", 9086699: "Heat Waves", 3720918: "Despacito", 9086691: "Royals", 1461025: "Fancy Like", 7434914: "Way 2 Sexy", 6093037: "Corta Venas", 6438692: "Need to Know", 8117542: "MONEY", 5746821: "Wild Side ", 9566779: "Knife Talk", 1683724: "Life Support", 5718817: "Save Your Tears", 2459304: "Ghost", 6382983: "Love Yourself", 7394792: "7 rings", } top_hits_playlist = [ 5390161, 7736243, 8267507, 4922599, 4559658, 9897626, 1461025, 5746821, 9566779, 5718817, 2459304, 6382983, 7394792 ] def display_full_playlist(): user_playlist_choice = input("Which playlists do you want to see? ") # 匹配歌单,支持大小写输入 if user_playlist_choice.lower() != "top hits": print("暂不支持该歌单") return # 打乱歌单顺序 shuffled_playlist = random.sample(top_hits_playlist, len(top_hits_playlist)) current_idx = 0 total = len(shuffled_playlist) while current_idx < total: # 每次取最多5首 end_idx = min(current_idx + 5, total) for song_id in shuffled_playlist[current_idx:end_idx]: print(video_id_to_title[song_id]) current_idx = end_idx # 全部输出完就退出,不再询问 if current_idx >= total: print("所有歌曲已展示完毕") break # 询问用户是否继续 answer = input("是否要查看更多歌曲?输入yes继续,其他输入退出:") if answer.lower() != "yes": break if __name__ == "__main__": display_full_playlist()
实现逻辑说明
- 导入
random模块实现歌单随机打乱,使用random.sample方法不改变原列表内容 - 修正了用户歌单输入的判断逻辑,转为全小写后匹配,兼容各种大小写输入格式
- 用
current_idx记录当前展示的位置,每次最多取5首输出,自动处理最后一批不足5首的情况 - 每次输出完一批后再询问用户是否继续,全部歌曲展示完毕后自动终止,无需用户额外操作
内容的提问来源于stack exchange,提问作者scjcodes
相关产品推荐
相关产品推荐

