开发者

How do I perform a random event in Python by picking a random variable?

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 pr开发者_如何学Goint it to the screen?


import random
print random.choice([dog, cat])

It's that simple. choice() takes a sequence and returns a random selection from it.


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).


I tried out the first method and second method, and none of them worked. So I am using a version of python which is 3.0, and this is the only thing that actually worked. The solutions are deprecated. Not true, wrong post.

Here is the working solution:

import random
dog = str([5])
cat = str([3])
variables = dog, cat
print(random.sample(variables, 1))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜