【发布时间】:2021-03-16 21:35:54
【问题描述】:
我有一个程序可以打印歌曲的首字母和他们的艺术家,你必须猜出这首歌。
我希望随机选择歌曲,但只显示一次,并且我希望在列表中的所有歌曲都显示后结束游戏。
这是我的文本文件“songs.txt”的示例:
Billie Eilish - 派对结束时
Ariana Grande - 男朋友
TMC - 无磨砂
命运之子 - 说出我的名字
阿黛尔 - 你好
凯蒂佩里 - 加州女孩
防弹少年团 - 主页
这是我的输出:
The first letter of the song is: H and the artist is: BTS
这是我的代码:
import random
def random_line(songs):
lines = open(songs).read().splitlines()
return random.choice(lines)
random =(random_line('songs.txt'))
artist = (random.split(' - ')[0])
song = (random.split(' - ',1)[1])
song_letter = song[0]
print ("The first letter of the song is: " + song_letter + " and the artist is: " + artist)
【问题讨论】:
-
为什么不只是 shuffle 列表并循环浏览改组的版本?
-
这个我不知道,我去研究一下,谢谢!
标签: python loops file random repeat