Python生成随机数的方法

random.random()用于生成

 1 n: a <= n <= b。如果 a
 1 2 3 4 5 6 print random.uniform(10, 20)   print random.uniform(20, 10)   #----  #18.7356606526   #12.5798298022   random.randint

 1 2 3 print random.randint(12, 20) #生成的随机数n: 12 <= n <= 20  print random.randint(20, 20) #结果永远是20  #print random.randint(20, 10) #该语句是错误的。 `

random.randrange

>>> import random
>>> random.randint(0,99)
21

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

>>> import random
>>> random.random()
0.85415370477785668
>>> random.uniform(1, 10)
5.4221167969800881

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

>>> import random
random.sample('abcdefghij',3)
['a', 'd', 'b']

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

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

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

posted on 2015-06-06 07:48  知识天地  阅读(160852)  评论(0编辑  收藏  举报