如何基于python中用户输入的选择从多个串联列表中打印随机项目?

时间:2019-04-09 19:16:17

标签: python

我想制作一个简单的应用程序,根据用户输入类型选择,建议艺术家听。我已经连接了lists(流派),它可以使用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中的随机项,但是输出是列表ab中的随机项,无论用户输入严格是a还是b

2 个答案:

答案 0 :(得分:2)

我相信您问题的根源是用户输入='a'下的<form id="zodiac"> <label for="month">Month:</label> <select id="month"> <option value='0' selected>January</option> <option value='1'>February</option> <option value='2'>March</option> <option value='3'>April</option> <option value='4'>May</option> <option value='5'>June</option> <option value='6'>July</option> <option value='7'>August</option> <option value='8'>September</option> <option value='9'>October</option> <option value='10'>November</option> <option value='11'>December</option> </select> <label for="day"> Day: </label> <input id="day" type='number' min='1' max='30' value='1'> <button type='button'>Done</button><br> <label for="output">Your sign is </label><output id='output'></output> </form> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>位。另外,您可以将提示放入您的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

尝试尝试获得“ z”,但它会出现:

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

please choose between a or b >>>b You should check out : z 是换行符,也是我如何提示"\n"在输出的下一行显示

答案 1 :(得分:2)

我认为问题是您正在使用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))