Article From:https://www.cnblogs.com/anningwang/p/9062774.html

If you do not understand the relationship between generating random numbers in Python and the most commonly used functions in the random module, the following article is the relationship between the Python generated random numbers and the most commonly used functions in the random module, hoping that you will gain something. Here is the articleThe introduction of the chapter.

random.random()It is used to generate a random number of points within a specified range. One of the two parameters is the upper limit and the other is the lower limit. If a > B, then a random number is generated

n Value: a < = n < = B. If a < B, then B < = n < = a.  

print random.uniform(10, 20) 
print random.uniform(20, 10) 
#----
#18.7356606526 
#12.5798298022 
random.randint

It is used to generate an integer within a specified range. The parameter a is the lower limit, the parameter B is the upper limit, and Python generates the random number.

print random.randint(12, 20) #The generated random number n: 12 < = n < = 20The result of print random.randint (20, 20) is always 20#print random.randint (20, 10)The statement is wrong.

The lower limit must be less than the upper limit.

random.randrange

From the specified range, according to the set of incremental base sets, this article is a partial introduction to the application of Python to generate random numbers.

Random integer:

import random
random.randint(0,99)

21

Random selection of 0 to 100 of the even numbers:

import random
random.randrange(0, 101, 2)

42

Random floating-point number:

import random
random.random() 

0.85415370477785668

random.uniform(1, 10)

5.4221167969800881

Random characters:

import random
random.choice('abcdefg&#%^*f')

‘d’

A specific number of characters are selected in multiple characters:

import random
random.sample('abcdefghij',3) 

[‘a’, ‘d’, ‘b’]

a = range(1000)
random.sample(a,5)

[394, 111, 89, 413, 402]

Select a specific number of characters in multiple characters to form a new string:

import random
import string
string.join(random.sample(['a','b','c','d','e','f','g','h','i','j'], 3)).replace(" ","")

‘fih’

Random selection of strings:

import random
random.choice ( ['apple', 'pear', 'peach', 'orange', 'lemon'] )

‘lemon’

Shuffle the cards:

import random
items = [1, 2, 3, 4, 5, 6]
random.shuffle(items)
print items

[3, 2, 5, 6, 4, 1]

Link of this Article: Python random usage method

Leave a Reply

Your email address will not be published. Required fields are marked *