random模塊是不能直接訪問的,需要引入該模塊后,通過random的靜態對象來調用該方法:
- 模塊導入:import random
- random常用方法:random.random(),random.choice(self,seq),random.randint(self,a,b),random.sample(population, k)
-
>>> help(random.random) #該幫助信息說明該方法可直接調用並返回0,1之間的隨機數
Help on built-in function random:random(...)
random() -> x in the interval [0, 1).
示例1:0-1隨機生成浮點數
>>> random.random()
0.3813265074990517
>>> random.random()
0.05383742352643661
示例2:0-1隨機生成保留2位小數的浮點數
>>> round(random.random(),2)
0.04
>>> round(random.random(),2)
0.69
- >>> help(random.choice) #從一個序列中隨機選取一個值並返回,該序列為元組、列表或者字符串
Help on method choice in module random:
choice(self, seq) method of random.Random instance
Choose a random element from a non-empty sequence.
示例1:字符串序列
>>> seq = 'abcdefg'
>>> random.choice(seq)
'a'
>>> random.choice(seq)
'f'
示例2:元組序列
>>> seq = (1,2,3,4,5,6)
>>> random.choice(seq)
3
>>> random.choice(seq)
2
示例3:列表序列
>>> seq = [1,2,3,4,5,6]
>>> random.choice(seq)
5
>>> random.choice(seq)
6
-
>>> help(random.randint) #從a-b區間中選取一個隨機數並返回
Help on method randint in module random:randint(self, a, b) method of random.Random instance
Return random integer in range [a, b], including both end points
示例:
>>> random.randint(1,20)
9
>>> random.randint(1,20)
15
- 從序列population中選取k個唯一不重復的值,且k的值不能大於population的長度
>>> help(random.sample)
Help on method sample in module random:sample(self, population, k) method of random.Random instance
Chooses k unique random elements from a population sequence.Returns a new list containing elements from the population while
leaving the original population unchanged. The resulting list is
in selection order so that all sub-slices will also be valid random
samples. This allows raffle winners (the sample) to be partitioned
into grand prize and second place winners (the subslices).Members of the population need not be hashable or unique. If the
population contains repeats, then each occurrence is a possible
selection in the sample.To choose a sample in a range of integers, use xrange as an argument.
This is especially fast and space efficient for sampling from a
large population: sample(xrange(10000000), 60) - 示例:
>>> random.sample(xrange(1000), 10) #從0-1000中隨機挑選10個唯一的值。
[905, 561, 89, 287, 575, 131, 711, 416, 678, 650]
>>> random.sample(xrange(10), 11) #選取的個數大於總序列的長度時會報錯,提示ValueError
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "E:\4software\python2.7\lib\random.py", line 323, in sample
raise ValueError("sample larger than population")
ValueError: sample larger than population