2013-02-13 97 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))