2013-02-13 95 views
-4

我必须创建一个提供选项列表的游戏,您可以选择一个gand,它会根据您的选择给出随机项目。例如。从Python中的前一个选择中随机选择

fruit = apple, orange, grapefruit 
berries = grape, raspberries, blackberries 
vegetable = carrot, lettuce, broccoli 

selection = raw_input("What is your selection? ") 

import random 
from random import choice 

print choice(selection) 

如果我说水果的话,水果的回应会随机发一封信。

+0

你试过什么吗?你有什么具体的问题? – millimoose 2013-02-13 10:52:06

+0

@MitchWheat:它下面的代码*是*尝试.. – 2013-02-13 10:52:18

回答

3

你不能在你的程序中引用变量。将选择存储在dict中。

selections = { 
    "fruit" : ("apple", "orange", "grapefruit"), 
    "berries" : ("grape", "raspberries", "blackberries"), 
    "vegetable" : ("carrot", "lettuce", "broccoli"), 
} 

... 

print choice(selections[selection]) 
0

你的代码,确实采取从输入一个随机的信。你可以通过打印selection

selection = raw_input("What is your selection? ") 

import random 
from random import choice 

print selection 
print choice(selection) 

>>> 
What is your selection? fruit 
fruit 
u 

你要采取从列表中随机项的基础上,输入键已经解决了这个,这是字典的工作。

from random import choice 
d = { 
'fruit' : ['apple', 'orange', 'grapefruit'], 
'berries' : ['grape', 'raspberries', 'blackberries'], 
'vegetable' : ['carrot', 'lettuce', 'broccoli'] 
} 

selection = raw_input("What is your selection? ") 
if selection in d: 
    print choice(d[selection]) 

>>> 
What is your selection? fruit 
grapefruit 
0

这会给你浆果之一,如果你回答选择“浆果”:

import random 
choices = { 'fruit' : ('apple', 'orange', 'grapefruit'), 
      'berries' : ('grape', 'raspberries', 'blackberries'), 
      'vegetable' : ('carrot', 'lettuce', 'broccoli'), 
      } 
selection = raw_input("What is your selection? ") 
print choices[selection][random.randint(0, 2)] 
-1

使用字典的解决方案是这样做的正确的方式,但你可以使用eval ()来实现你想要的东西:

fruit = ['apple', 'orange', 'grapefruit'] 
berries = ['grape', 'raspberries', 'blackberries'] 
vegetable = ['carrot', 'lettuce', 'broccoli'] 

selection = raw_input("What is your selection? ") 

import random 

from random import choice 

print choice(eval(selection))