嗨,我刚刚开始学习 Python,我正在使用《以困难的方式学习 Python》一书,练习之一是构建一个简单的游戏。我想从列表中为用户提供选项。
例如,我会创建一个名为“动物”的列表,其中包括 3 种动物:狮子、老虎和鱼。可以提供从列表中选择的元素。我很确定是这样,但我只是不知道如何。
我在想这样的事情(显然是错误的,但我认为这有助于理解我的意思)
animals = ['Lion', 'Tiger', 'Fish']
print "which of these animals is your favourite?"
favourite = raw_input(animals[0] or animals[2])
if favourite = "Lion':
print "Nice choice"
else:
print "Bad choice"
我再次强调,我知道上面的内容确实很糟糕,但本质上我想提供列表中的某些项目作为 raw_input 的选项。在上面的例子中是 0 项和 2 项。
预先感谢您的帮助。
最佳答案
favourite = raw_input(' or '.join(animals))
这将从列表 animals
中获取所有字符串,并用 or
将它们连接在一起,这样你最终会得到
Lion or Tiger or Fish
if you want to add a question mark and space to the end, you can do
favourite = raw_input(' or '.join(animals) + '? ')
还有,上线了
if favourite = "Lion':
您的引号不匹配 - 确保使用双引号或单引号,而不是各用一个。您还需要使用 ==
来比较两个事物; =
用于赋值,而不是比较。
我可能会这样做
animal_string = ' or '.join(animals)
favourite = raw_input("Which of these animals is your favourite:\n{}? ".format(animal_string))
它首先生成动物字符串,然后将选项格式化为新行中的问题(因为 \n
),并在后面添加 ?
。
关于python - 从列表中提取 raw_input 选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7301040/