我目前正在做一个与音乐播放列表有关的项目,我需要能够打印特定歌手和歌曲的首字母,以便用户猜测歌手和歌曲必须是随机强>。我为每个艺术家和歌曲制作了一个单独的阵列,但是我不知道如何随机选择这些阵列之一供我使用。
这是我的数组代码:
BTS = ["Idol", "BTS"]
SWIFTY = ["Love Story", "Taylor Swift"]
RUTH = ["Lost Boy", "RuthB"]
ED = ["Perfect", "Ed Sheeran"]
ARIANA = ["No Tears Left To Cry", "Ariana Grande"]
DRAKE = ["In My Feeling", "Drake"]
RICKY = ["La Vida Loca", "Ricky Martin"]
IU = ["BBIBBI", "IU"]
BTS2 = ["Magic Shop", "BTS"]
PSY = ["Gangnam Style", "PSY"]
如何随机选择这些阵列之一?
答案 0 :(得分:1)
random.choice()可以解决问题。
import random
random.choice((BTS,SWIFTY,RUTH,ED,ARIANA,DRAKE,RICKY,IU,BTS2,PSY))
您应该使用字典,如果轨道数量增加,它将使您的代码更易于维护:
musics = {
'BTS' : ["Idol", "BTS"],
'SWIFTY' : ["Love Story", "Taylor Swift"],
'RUTH' : ["Lost Boy", "RuthB"],
'ED' : ["Perfect", "Ed Sheeran"],
'ARIANA' : ["No Tears Left To Cry", "Ariana Grande"],
'DRAKE' : ["In My Feeling", "Drake"],
'RICKY' : ["La Vida Loca", "Ricky Martin"],
'IU' : ["BBIBBI", "IU"],
'BTS2' : ["Magic Shop", "BTS"],
'PSY' : ["Gangnam Style", "PSY"]}
import random
random.choice(list(musics.values()))