random模块python

时间:2014-10-31 13:25:25   收藏:0   阅读:363

random是用于生成随机数的,我们可以利用它随机生成数字或者选择字符串。

1
2
import random
random.random()   #输出 0.5487876445645461
1
2
3
4
import random
random.uniform(10,20) #输出 15.999997038152358
random.uniform(20,10) #输出 12.718038067741021
random.uniform(10,10) #输出 10.0
1
2
3
4
import random
random.randint(10,20) #输出 12
random.randint(10,10) #输出 10
random.randint(20,10) #Error
1
2
3
4
import random
random.randrange(10,100) #输出为10到100间的任意数
random.randrange(10,100,4) #输出为10到100内以4递增的序列[10,14,18,22...]
random.choice(range(10,100,4)) #输出在结果上与上一条等效
1
2
3
4
5
6
7
8
9
import random
random.choice(range(10)) #输出0到10内随机整数
random.choice(range(10,100,2)) #输出随机值[10,12,14,16...]
random.choice("I love python") #输出随机字符I,o,v,p,y...
random.choice(("I love python")) #同上
random.choice(["I love python"]) #输出“I love python”
random.choice("I","love","python") #Error
random.choice(("I","love","python")) #输出随机字符串“I”,“love”,“python”
random.choice(["I","love","python"]) #输出随机字符串“I”,“love”,“python”
1
2
3
4
import random
list=[‘I‘,‘love‘,‘python‘,‘very‘,‘much‘]
random.shuffle(list)
print list     #输出乱序list
1
2
3
4
5
6
7
8
9
10
import random
a=‘123456789‘
b=[1,2,3,4,5,6,7,8,9]
c=[‘a‘,‘b‘,‘c‘,‘d‘,‘e‘]
random.sample(a,3)
random.sample(b,3)
random.sample(c,3#随机取三个元素最为一个片段返回[6,4,3]
print a
print b
print c    #a,b,c值不变

原文:http://www.cnblogs.com/wipy/p/4064719.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!