# Python生成随机数的方法【转载】Zhyancy

random.random()用于生成

print random.uniform(10, 20)
print random.uniform(20, 10)
18.7356606526
12.5798298022
random.randint
• 1
• 2
• 3
• 4
• 5

print random.randint(12, 20) #生成的随机数n: 12 <= n <= 20
print random.randint(20, 20) #结果永远是20
print random.randint(20, 10) #该语句是错误的。下限必须小于上限
• 1
• 2
• 3

# random.randrange

import random
random.randint(0,99)
>>>21
• 1
• 2
• 3

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

import random
random.random()
>>>0.85415370477785668
random.uniform(1, 10)
>>>5.4221167969800881
• 1
• 2
• 3
• 4
• 5

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

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

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

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

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

08-06 2324
07-13 3万+
08-18
09-28 2万+
03-27 1646
08-13 114
10-12 1万+
04-20 302
05-07 3万+
07-10 5966