【问题标题】:I want to create a set of lists that after some input from the user one will be randomly selected我想创建一组列表,在用户输入一些内容后,将随机选择一个列表
【发布时间】:2023-02-04 05:19:58
【问题描述】:

我对这一切完全陌生,我不知道自己在做什么。我只想要一个简单的选择器,它会询问“你觉得什么类型?”然后根据输入是摇滚、说唱、独立音乐还是我以后添加的任何内容,在列表中随机选择一张专辑。

from random import choice

def lists()
    rock_albums = ['Dark Side of the Moon - Pink Floyd']
    rap_albums = ['Igor - Tyler, the Creator']
    indie_albums = ['Currents - Tame Impala']

print("What genre are you feeling?")
genre = input()

if input("rock"):
    rock = random.choice(albums_rock)
    print(rock)

我没有进一步添加更多专辑或其他流派的任何其他 if 语句。

我不知道还能尝试什么。我从一个更大的列表开始,可以从中随机选择,这个列表很有效,所以我前进了。现在我卡住了。

【问题讨论】:

  • 您发布的代码有语法错误。在 def lists() 之后需要一个冒号。
  • 只需将 if input("rock"): 替换为 if genre == "rock":
  • 由于您对所有这些都是全新的并且不知道您在做什么,我会高度建议您浏览一个以结构化方式解释这些概念的教程,而不是让自己陷入可能无法解决的问题。

标签: python python-3.x list


【解决方案1】:

您可以将所有流派存储在字典中,然后根据键从适当的列表中选择。

import random
albums = {
    'rock' : ['Dark Side of the Moon - Pink Floyd'],
    'rap' : ['Igor - Tyler, the Creator'],
    'indie' : ['Currents - Tame Impala']
}
genre = input("What genre are you feeling?
")
if genre in albums:
    print(random.choice(albums[genre]))

【讨论】:

    猜你喜欢
    • 2021-01-14
    • 1970-01-01
    • 2021-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多