Introduction to Random module functions
Choice ()
Gets a random element from the sequence. list, tuple, string all belong to sequence
#随机取一个数choice ([1, 2, 3, 5, 9])
Randint ()
Used to generate an integer within a specified range. Where parameter A is the lower limit, parameter B is the upper limit, the generated random number n:a <= n <= B
Print Random.randint (12,20) #生成的随机数n: <= n <= print random.randint (20,20) #结果永远是20 #print Random.randint ( #该语句是错误的). The lower limit must be less than the upper limit.
Random ()
Used to generate a random number of 0 to 1 points: 0 <= N < 1.0
Uniform ()
Random.uniform (A, b), used to generate a random number of characters in a specified range, two parameters one of which is the upper bound, and the other is the lower limit. If a > B, the generated random number n:a <= n <= B. If a <b, then B <= N <= A.
Print Random.uniform (10,20) print random.uniform (20,10) #----Results (different results on various machines) #18.7356606526
Randrange ()
The function prototype for Random.randrange is: Random.randrange ([start], stop[, step]), which gets a random number from the specified range, in the collection incremented by the specified cardinality. such as: Random.randrange (10, 100, 2), the result is equivalent from [10, 12, 14, 16, ... 96, 98] gets a random number in the sequence. Random.randrange (10, 100, 2) is equivalent to Random.choice (range (10, 100, 2) on the result.
Random.shuffle
The function prototype for random.shuffle is: random.shuffle (x[, Random]), which is used to disrupt elements in a list. Such as:
p = [' Python ', ' is ', ' powerful ', ' simple ', ' and so ' on ... '] random.shuffle (p) print P #----Results (results may differ on different machines.) #[' powerful ', ' simple ', ' was ', ' Python ', ' and so on ... ']
Random.sample
The function prototype for random.sample is: random.sample (sequence, k), which randomly fetches fragments of the specified length from the specified sequence. The sample function does not modify the original sequence.
list = [1, 2, 3, 4, 5, 6, 7, 8, 9, ten] slice = random.sample (list, 5) #从list中随机获取5个元素, return print as a fragment slice
print list #原有序列并没有改变.
Python random module