I can select randomly from a list... but how do I use this as a variable for different commands? Python
Lets say I have the following:
foo = ('animal', 'vegetable', 'mineral')
I want to be able to randomly select from the list THEN, depending on which one is selected, have a set of commands to follow.开发者_开发百科
For instance, if 'animal' was randomly selected, I want the message print('rawr I'm a tiger'), or if it was 'vegetable' print('Woof, I'm a carrot') or something.
I know to randomly select it is:
from random import choice
print choice(foo)
but I don't want the choice to be printed, I want it to be secret.
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())]
If you wanted to branch off to some other sections in an app, something like this might suite better:
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()
If you don't want to print it, just assign it to a variable:
element = choice(foo)
To then pick the appropriate message, you might want a dictionary from the element type (animal/mineral/vegetable) to a list of random messages associated with that element type. Take the list from the dictionary, then pick a random element to print...
You just assign your randomly selected item to a variable.
>>> 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"
or more condensed if you don't have to keep a tuple:
messages[random.choice(messages.keys())]
精彩评论