python - 从列表中提取 raw_input 选项

标签 python list input

嗨,我刚刚开始学习 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/

相关文章:

c++ - 读入二维 vector

c++ - 从文本文件中读取整数

python - 预测泰坦尼克号数据集中年龄的 Nan 值

python - asyncio.create_task 与等待

python - 使用 python odeint scipy 求解一系列 ode 时分割状态向量

python - 如何有效地比较两个无序列表(不是集合)?

css - 输入范围 - 高度 0 仅适用于 firefox

javascript - 如何在 Robot Framework 中滚动到页面的右下角?

Java:将整数数组划分为具有随机值的子数组?

python - 在列表中查找与另一个列表中的元素近似相等的元素的索引