The Python random module is commonly used

  • 2020-04-02 14:20:18
  • OfStack


import random
print random.random()

Gets a floating point number less than 1


import random
random.randint(1,10)

Gets an integer from 1 to 10


import random
print random.uniform(0,2)

Gets a floating point number greater than 0 and less than 2


import random
print random.randrange(1,10,4)

Gets a random number with a size of 4 in steps 1 to 10


import random
a=[1,2,3,4,5]
random.choice(a)

Pick a random element from list a


import random
a=[1,2,3,4,5]
random.shuffle(a)

Shuffle the order of the elements in list a


import random
a=[1,2,3,4,5]
random.sample(a,3)

Pick 3 elements from list a in random order (an element can only be pulled out once, so the number of elements to pull out must not be greater than the number of elements in the list)


Related articles: