In daily development, we often need to use random numbers, so this article will sort out the basic usage of random numbers.
Random generation of floating point numbers between 0 and 1
Random. Random () returns a float between [0.0,1.0), which may yield a 0 but never a 1.
import random
val = random.random()
print(val)
Copy the code
Random generation of floating point numbers between A and B
Random. Uniform (a, b) This method returns floating point numbers between [A, B], which may yield A, but never B.
import random
val = random.uniform(1.10)
print(val)
Copy the code
Randomly generate integers between A and B
Random.randint (a, b) This method returns a random integer between [a,b], which may be either a or B.
import random
val = random.randint(1.10)
print(val)
Copy the code
If you don’t want to generate b, you can do the following:
Random.randrange (a, b) This method returns a random integer between [a,b], which may be a, but will never produce B.
import random
val = random.randrange(1.10)
print(val)
Copy the code
Randrange (10, 100, 2). The result is the same as choosing a number randomly from 10,12,14,16…100.
import random
val = random.randrange(10.100.2)
print(val)
Copy the code
Retrieves a random element from the list
Random.choice (l) This method returns any element in the list.
import random
l = [1.2.3.4.5.6]
val = random.choice(l)
print(val)
Copy the code
Shuffle the order of the elements in the list
Random.shuffle (l) This method returns the list elements out of order.
import random
l = [1.2.3.4.5.6]
random.shuffle(l)
print(l)
#out [6, 1, 5, 3, 4, 2]
Copy the code
We found that the scrambled data in the original data operation, if we need the original data, it is best to use the copy method in the copy module before the scrambled data.
Pick n random elements from the list
Random. Sample (L, n) This method will randomly fetch n elements from the list.
import random
l = [1.2.3.4.5.6]
val = random.sample(l,3)
print(val)
#out [4, 2, 1]
Copy the code
Those are some of the most basic uses of randomness in Python.
The following is the qr code picture of my official account, welcome to follow.