How do I perform a random event in Python by picki

2020-03-26 04:20发布

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?

标签: python random
2条回答
Juvenile、少年°
2楼-- · 2020-03-26 04:49
import random
print random.choice([dog, cat])

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

查看更多
别忘想泡老子
3楼-- · 2020-03-26 05:01

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

查看更多
登录 后发表回答