Let's say I have to variables, dog and cat. Dog = 5, and cat = 3. How would I tell Python to pick one of these variables by random and print it to the screen?
+8
A:
import random
print random.choice([dog, cat])
It's that simple. choice()
takes a sequence and returns a random selection from it.
Rafe Kettler
2010-10-22 16:34:31
It's worth pointing out that dog and cat can be anything: functions, string keys into a dictionary, numbers...so if you want to perform a random event, you can have them be functions and `random.choice([dog, cat])()`.
Nathon
2010-10-22 16:56:03
@Nathon: good point. The argument passed to `choice()` can be anything iterable, and in Python it's very easy to make a list composed of literally anything.
Rafe Kettler
2010-10-22 16:58:59
+1
A:
You can put all the variables you want to choose from in a list and use the random module to pick one for you.
import random
dog = 5
cat = 3
vars = [dog,cat]
print random.sample(vars, 1)
The sample method takes two arguments: the population you want to choose from, and the number of samples you want (in this case you only want one variable chosen).