pyt*_*ace 0 python printing random list choice
可以说我有以下内容:
foo = ('animal', 'vegetable', 'mineral')
Run Code Online (Sandbox Code Playgroud)
我希望能够从列表中随机选择THEN,具体取决于选择哪一个,具有一组要遵循的命令.
例如,如果随机选择"动物",我想要打印消息('rawr I \'ma tiger'),或者如果它是'蔬菜'打印('Woof,我是胡萝卜')或其他东西.
我知道随机选择它是:
from random import choice
print choice(foo)
Run Code Online (Sandbox Code Playgroud)
但我不希望打印的选择,我希望它是秘密的.请帮忙.
import random
messages = {
'animal': "rawr I'm a tiger",
'vegetable': "Woof, I'm a carrot",
'mineral': "Rumble, I'm a rock",
}
print messages[random.choice(messages.keys())]
Run Code Online (Sandbox Code Playgroud)
如果你想分支到应用程序中的其他部分,这样的事情可能更好:
import random
def animal():
print "rawr I'm a tiger"
def vegetable():
print "Woof, I'm a carrot"
def mineral():
print "Rumble, I'm a rock"
sections = {
'animal': animal,
'vegetable': vegetable,
'mineral': mineral,
}
section = sections[random.choice(sections.keys())]
section()
Run Code Online (Sandbox Code Playgroud)