python之random模块

random方法得到一个0.0到1.0之间的浮点数:

import random
a=random.random()
print (a)

E:\python36\python3.exe E:/pj/test/test.py
0.3062280038416443

randint得到一个0,10之间的整数:

import random
a=random.randint(0,11)
print (a)

E:\python36\python3.exe E:/pj/test/test.py
8

uniform得到一个1,10之间的浮点数:

import random
a=random.uniform(1,11)
print (a)

E:\python36\python3.exe E:/pj/test/test.py
7.868748165867887

randrange得到一个1,10之间的整数,间隔为2得可选取:

import random
a=random.randrange(1,11,2)
print (a)

E:\python36\python3.exe E:/pj/test/test.py
7

choice分别对列表,元祖,字符串进行随机化选取:

import random
d1=['a','b','c','d']
d2=('a','b','c','d')
d3="abcd"
a1=random.choice(d1)
a2=random.choice(d2)
a3=random.choice(d3)
print (a1)
print (a2)
print (a3)

E:\python36\python3.exe E:/pj/test/test.py
d
b
c

shuffle对列表进行随机排序:

import random
d=[1,2,3,4]
a=random.shuffle(d)
print (d)

E:\python36\python3.exe E:/pj/test/test.py
[4, 1, 2, 3]

sample按照指定长度随机选取元素,作为一个片段返回:

import random
d="apple"
a=random.sample(d,2)
print (a)

E:\python36\python3.exe E:/pj/test/test.py
['p', 'a']
posted @ 2018-03-05 17:01  若爱以星光为牢  阅读(245)  评论(0编辑  收藏  举报