Summary of Python3 built in module random random method

  • 2021-07-18 08:11:25
  • OfStack

Preface

random is a module related to random numbers in Python, and its essence is a pseudo-random number generator. We can use random module to generate various random numbers and some operations based on random numbers.

Generate random number correlation

Generate floating-point numbers between 0 and 1


import random
r = random.random()
print(r)
r = random.random()
print(r)

Example results:


0.9928249533693085
0.474901555446297

Generates floating-point numbers within the specified range


import random
r = random.uniform(1, 100)
print(r)
r = random.uniform(100, 1)
print(r)

Example results:


69.0347778479432
3.2085981780335118

That is, the two ends of the random range can be placed at will, without the need for small left and large right.

Generates integers in the specified range


import random
r = random.randint(1, 100)
print(r)

Example results:


58

randrange Generates Random Integers

Using randrange to generate incremental sequence and then randomly return 1 integer from the sequence


import random
# 0 - 100  Random sequence 
r = random.randrange(101)
print(r)
# 10 - 100  Random sequence 
r = random.randrange(10, 101)
print(r)
# 10 - 100  And the steps (intervals) are 3  Adj.   Random sequence 
r = random.randrange(10, 101, 3)
print(r)

Example results:


52
60
46

Sequence processing correlation

Get 1 random element from the sequence

Use random. choice (iter) to get a random element from any sequence, such as list, tuple, dictionary, etc.


import random
S = 'I like Python'
#  Generate 1 List 
L = S.split(' ')
print(L)
r = random.choice(L)
print(r)

Disturb the order of sequence elements

Using random. shuffle (iter) to scramble the arrangement of elements in the original sequence


import random
S = 'I like Python'
#  Generate 1 List 
L = S.split(' ')
print(L)
random.shuffle(L)
print(L)

Example results:


0.9928249533693085
0.474901555446297
0

Randomly fetching multiple elements from a sequence

Using random. sample () sequence to get a specified number of elements randomly and return a sequence of specified length without changing the original sequence


0.9928249533693085
0.474901555446297
1

Example results:


0.9928249533693085
0.474901555446297
2

Related articles: