【问题标题】:How to print random items from multiple concatenated lists based on user input choice in python?python - 如何根据python中的用户输入选择从多个连接列表中打印随机项目?
【发布时间】:2019-04-09 19:16:16
【问题描述】:

我想制作一个简单的应用程序,根据用户输入的流派选择建议艺术家收听。我已经连接了列表(流派),它可以使用 random.choice 从任何列表中打印随机项目。但是我希望它只从用户输入的列表中打印一个随机项目,而不是随机列表中的随机项目。

尝试在 elif 和 else 之间进行更改。尝试制作 for 循环,但没有太大成功。

import random
a= ["x", "y"]
b= ["z", "k"]
print("please choose between a or b")
answer = input ()
if answer == "a":
    print("You should check out : " , random.choice(a+b))
elif answer == "b":
    print("You should check out : " , random.choice(b))

当用户输入“a”时,我希望输出是列表a 中的随机项,当用户输入“b”时,我希望输出是列表b 中的随机项,但输出是随机项无论用户输入是严格的a 还是b,都来自列表ab

【问题讨论】:

    标签: python


    【解决方案1】:

    我认为问题在于您正在使用random.choice(a+b) 而不是random.choice(a)。以下对我来说很好

    import random
    a= ["x", "y"]
    b= ["z", "k"]
    print("please choose between a or b")
    answer = input ()
    if answer == "a":
        print("You should check out : " , random.choice(a))
    elif answer == "b":
        print("You should check out : " , random.choice(b))
    

    【讨论】:

    • 我也试过了,但它不打印列表 b 中的项目。仅来自我的列表 a (x,y)。它不会显示 z 或 x。
    【解决方案2】:

    我相信您问题的根源是用户输入 = 'a' 下的 a+b 位。此外,您可以将提示放入您的 input() 语句中。当我跑步时,它似乎对我很好:

    import random
    
    a = ["x", "y"]
    b = ["z", "k"]
    answer = input("please choose between a or b \n>>>")
    if answer == "a":
        print("You should check out : ", random.choice(a))
    elif answer == "b":
        print("You should check out : ", random.choice(b))
    

    示例输出:

    please choose between a or b 
    >>>a
    You should check out :  x
    
    please choose between a or b 
    >>>b
    You should check out :  k
    

    尝试了几次得到“z”,但它会显示出来:

    please choose between a or b 
    >>>b
    You should check out :  z
    

    "\n" 是一个换行符,这也是我在输出的下一行得到提示 >>> 的方式

    【讨论】:

    • 我也试过了,但它不打印列表 b 中的项目。仅来自我的列表 a (x,y)。它不会显示 z 或 x。基本上与其他答案相同,只是我不明白您的代码中 \n>>> 的目的。
    • @user11334298 如果您按照发布的方式运行我的代码,它肯定会显示“x”或“z”。检查我的示例输出!
    • 你是对的。我会看看我的代码是否还有其他问题。
    • 我添加了额外的或者搞砸了。我只是在 if 语句中添加了另一个选项。它有效
    猜你喜欢
    • 1970-01-01
    • 2012-09-12
    • 1970-01-01
    • 1970-01-01
    • 2017-02-19
    • 1970-01-01
    • 1970-01-01
    • 2013-01-13
    • 1970-01-01
    相关资源
    最近更新 更多