如何在Python中选择与用户输入的随机交互?

2024-05-19 05:52:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望能够从一个笑话列表中随机选择一个笑话,并继续使用用户输入的笑话(不管是敲门还是其他什么)。在

我知道我需要做什么,有一个简单的敲门笑话与用户互动,但我想能够做几个不同的随机。在

所以在伪代码方面,我希望它看起来像这样:

print("Would you like to hear a joke?")
answer = input()
if answer == ("Yes"):
   choose joke from list of jokes ["joke a", "joke b", "joke c"]
   print("randomly chosen joke")
   continue on with user input
else:
   sys.exit()

Tags: to代码用户answeryou列表inputif
3条回答

其他的回答和评论都建议使用random.choice,但我认为在这种情况下使用它实际上是错误的,因为它可能在同一个会话中重复同一个笑话不止一次。我怀疑这对用户来说是一个糟糕的体验,所以这里有一个替代方案。在

{t{t>用户不想按顺序重复一个或多个笑话:

import random

jokes = [x, y, z]     # these could be strings, or functions as suggested by GraphicsNoob

random.shuffle(jokes) # put the list in a random order

it = iter(jokes)      # an iterator over the shuffled list

first = next(it)
print(first)          # tell the first joke, could be first() instead

for joke in it:       # loop over the rest of the jokes
    response = input("Would you like to here another joke?"):   # ask about more
    if response.lower().startswith("n"):                   # stop if the user says "no"
        break
    print(joke)       # tell the next joke, could be joke() if you're using functions
joke = random.choice(["joke a", "joke b", "joke c"])

从列表中随机选择一个元素可以这样做

import random
joke_list = ['joke1', 'joke2', 'joke3']
random.choice(joke_list)

但实际上,这只是选择一个字符串。你想要的是选择一个交互的东西。这可以用这种方法来完成

^{pr2}$

所以总结一下:让你的笑话函数代替字符串,这样它们就可以成为一个独特的交互,列出一个函数列表,用random.choice选择一个随机元素

相关问题 更多 >

    热门问题