Suppose you have a relationship with a few of the most frequently used functions in Python and the random module. The following article is the relationship between Python generation random numbers and the most frequently used functions in the random module, and hopefully you will reap some of the benefits, as the following is an introduction to this article.
Random.random () is used to generate
Used to generate a random number of points within a specified range, and one of the two parameters is the upper limit. One is the lower limit.
Assuming a > B, a random number is generated
1 |
n: a < = n < = b。
假设 a <b, 则 b < = n < = a。
|
1 2 3 4 5 6 |
print random.uniform ( 10 20 ) print Random.uniform ( 20 10 ) #---- # 18.7356606526 # 12.5798298022 |
Used to generate an integer within a specified range. The number A is the lower limit, and the number of references is the upper limit. Python generates random numbers
1 2 3 |
print random.randint( 12 , 20 ) #生成的随机数n: 12 <= n <= 20 print random.randint( 20 , 20 ) #结果永远是20 #print random.randint(20, 10) #该语句是错误的。
|
The lower limit must be less than the upper limit.
Random.randrange
From within the specified range. In the collection that increments by the specified cardinality, this article is a partial introduction to the Python-generated random number application.
Random integers:
>>> Import Random
>>> Random.randint (0,99)
21st
Randomly select even numbers between 0 and 100:
>>> 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 '
Select a specific number of characters in more than one character:
>>> Import Random
Random.sample (' Abcdefghij ', 3)
[' A ', ' d ', ' B ']
Select a specific number of characters to form a new string in multiple characters:
>>> Import Random
>>> Import String
>>> String.Join (Random.sample ([' A ', ' B ', ' C ', ' d ', ' e ', ' f ', ' g ', ' h ', ' I ', ' J '], 3)). R
Eplace ("", "" ")
' FIH '
Randomly pick a string:
>>> Import Random
>>> random.choice ([' Apple ', ' pear ', ' peach ', ' orange ', ' Lemon '])
' Lemon '
Shuffle:
>>> Import Random
>>> items = [1, 2, 3, 4, 5, 6]
>>> random.shuffle (items)
>>> Items
[3, 2, 5, 6, 4, 1]
Python random number Generation method