python - 如何从用户那里获取输入,将它们放入列表中,然后从中随机选择一个,而无需多次询问
问题描述
这是我学习编程的第四天,所以我对它很陌生。我试图在一个问题中获取用户的信息(爱好)并将它们保存到一个列表中,然后将他们选择的爱好之一回馈给用户。这就是我想出的
import random
fav_hobbies = []
hobbies = input("what are your favourite hobbies?(cooking, writing,ect) ").lower()
fav_hobbies.append(hobbies)
situation = input("so are you bored now?(answer with yes or no): ").lower()
if situation == "yes":
print("you should try " + random.choice(fav_hobbies))
elif boredom_situation == "no":
print("awesome! have a nice day!")
问题是,它不是在用户选择的单词中选择一个单词,而是打印他们所说的所有内容。
我该如何解决?
解决方案
您只是接受来自用户的字符串并将其按原样存储而无需拆分。
假设您接受空格分隔的输入,您可以在以下位置执行此操作:
fav_hobbies = list(input("what are your favourite hobbies?(cooking, writing,ect) ").lower().split())
import random
fav_hobbies = list(input("what are your favourite hobbies?(cooking, writing,ect) ").lower().split())
situation = input("so are you bored now?(answer with yes or no): ").lower()
if situation == "yes":
print("you should try " + random.choice(fav_hobbies))
elif boredom_situation == "no":
print("awesome! have a nice day!")
如果您使用其他分隔符,
,则可以将其添加到split(',')
推荐阅读
- python - Threadpool Executor 仍然在 Python 中阻塞
- python - 根据值组合在字典列表中查找重复对象
- asp.net-mvc - 使用 AuthorizeAttribute 而不在失败时触发 URL 重定向?
- elasticsearch - 无法解析 _doc 类型:Elasticsearch 7.x 中的映射错误
- c# - 在 web-api 中调用特定方法时如何调用信号器集线器?
- symfony - 如何在数据库中存储星期几并使用 Symfony/Twig 显示它们的名称?
- centos7 - centos 未更新,centos 7.8 (2003)
- postgresql - Postgresql 错误:无法建立连接
- spring - thesisMongoProject.controller.ScoreController 中方法 createScore 的参数 0 需要一个 'thesisMongoProject.Score' 类型的 bean
- scala - 使用scala spark如何仅打印从HTTP post调用返回的响应正文值