从列表中提取raw_input选项

2 投票
2 回答
3572 浏览
提问于 2025-04-17 01:25

你好,我刚开始学习Python,我在用一本叫《Learn Python the Hard Way》的书,其中有一个练习是要做一个简单的游戏。我想从一个列表中给用户提供选项。

比如,我会创建一个叫做动物的列表,里面包括三种动物:狮子、老虎和鱼。请问可以从这个列表中提供选定的元素吗?我很确定可以,但我就是不知道怎么做。

我在想像这样做(当然这明显是错的,但我觉得这样可以帮助理解我的意思)

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个项目。

提前谢谢你的帮助。

2 个回答

1

这样怎么样?

favourite = raw_input("which of these animals is your favourite? "+",".join([str(a)+":"+b for a,b in enumerate(animals)])+">")
fav = animals[int(favourite)]
print fav+" is a nice choice indeed!. The big bear will kill you anyway. Good bye."
3
favourite = raw_input(' or '.join(animals))

这段代码会把列表 animals 中的所有字符串用 or 连接起来,所以最后你会得到这样的结果:

Lion or Tiger or Fish

如果你想在最后加一个问号和空格,可以这样做:

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),最后在后面加上 ?

撰写回答