0

可以说我有以下内容:

foo = ('animal', 'vegetable', 'mineral')

我希望能够从列表中随机选择然后,根据选择的一个,有一组命令要遵循。

例如,如果 'animal' 是随机选择的,我想要消息 print('rawr I\'ma tiger'),或者如果它是 'vegetable' print('Woof, I'm a carrot') 或其他内容。

我知道随机选择它是:

from random import choice
print choice(foo)

但我不想打印选择,我希望它是秘密的。请帮忙。

4

4 回答 4

5
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())]

如果您想分支到应用程序中的其他部分,这样的内容可能更适合:

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()
于 2011-04-01T06:35:08.800 回答
1

如果您不想打印它,只需将其分配给一个变量:

element = choice(foo)

然后要选择适当的消息,您可能需要从元素类型(动物/矿物/植物)到与该元素类型关联的随机消息列表的字典。从字典中取出列表,然后选择一个随机元素进行打印...

于 2011-04-01T06:34:45.673 回答
1

您只需将随机选择的项目分配给一个变量。

于 2011-04-01T06:35:38.697 回答
0
>>> messages = {"animal" : "Rawr I am a tiger", "vegtable" :"Woof, I'm a carrot", "mineral" : "I shine"}
>>> foo = ('animal', 'vegtable', 'mineral')                                     >>> messages[random.choice(foo)]"Woof, I'm a carrot"

>>> messages[random.choice(foo)]
"Woof, I'm a carrot"

如果您不必保留元组,则更精简:

messages[random.choice(messages.keys())]
于 2011-04-01T06:37:38.857 回答