These days, we need to randomly extract a few numbers from the heap, So we re-studied the random module.
The following describes common functions in random.
Prerequisites: You need to import the random module.
>>> Import random
1. Random. Random
Random. Random () is used to generate a random number ranging from 0 to 1: 0 <= n <1.0
>>> Random. Random () # random float X,
2. Random. Uniform
The original function of random. Uniform is: Random. Uniform (a, B), used to generateRandom Number of Characters in the specified rangeOne of the two parameters is the upper limit and the other is the lower limit. If A> B, the random number N: A <= n <= B. If a <B, B <= n <=.
>>> Random. Uniform (1, 10) # random float X,
3. Random. randint
The prototype of the random. randint () function is random. randint (a, B), which is used to generate an integer in the specified range. Where parameter A is the lower limit, parameter B is the upper limit, and the generated random number N: A <= n <= B
>>> Random. randint (10,100)
4. Random. randrange
The prototype of the random. randrange function is random. randrange ([start], stop [, step]). a random number is obtained from the set that increments by the specified base number within the specified range. For example: Random. randrange (10,100, 2), the result is equivalent to obtaining a random number from the [10, 12, 14, 16,... 96, 98] sequence. Random. randrange (10,100, 2) is equivalent to random. Choice (range (10,100, 2) in the result.
Randomly select an even number between 0 and 100:
>>> Import random
>>> Random. randrange (0,101, 2)
5. Random. Choice
Random. Choice gets a random element from the sequence. The function prototype is random. Choice (sequence ). The sequence parameter indicates an ordered type. Sequence is not a specific type in Python, but a series of types. List, tuple, and string all belong to sequence. For sequence, see the python manual data model chapter.
>>> Random. Choice ('abcdefg & # % ^ * F') # random character
'D'
>>> Random. Choice (['apple', 'pear ', 'peach', 'Orange ', 'lemon']) # randomly select a string:
'Limon'
6. Random. Shuffle
The original function of random. Shuffle is random. Shuffle (X [, random]), which is used to disrupt elements in a list. For example:
P = ["Python", "is", "powerful", "simple", "and so on..."]
Random. Shuffle (P)
Print P
# Result (because it is random, your results may be different .)
# ['Powerful', 'simple', 'is', 'python', 'and so on... ']
P = ["Python", "is", "powerful", "simple", "and so on..."]
7. Random. Sample
The prototype of the random. sample function is random. Sample (sequence, k). Fragments of the specified length are randomly obtained from the specified sequence. The sample function does not modify the original sequence. If K is greater than the number of sequence elements, an error is returned.