# random各种使用方法
import
random
# 随机生成[0.1)的浮点数
print
(
"random():"
, random.random())
# 随机生成1000-9999之间的整数
print
(
"randint(1000, 9999):"
, random.randint(
1000
,
9999
))
# 随机生成0-20之间的偶数
print
(
"randrange(0, 21, 2):"
, random.randrange(
0
,
21
,
2
))
# 随机生成0-20之间的浮点数
print
(
"uniform(0, 20):"
, random.uniform(
0
,
20
))
# 从序列中随机选择一个元素
list_string
=
[
'a'
,
'b'
,
'c'
,
'd'
,
'e'
]
print
(
"choice(list):"
, random.choice(list_string))
print
(
"choice(string):"
, random.choice(
'abcd'
))
# 对列表元素随机排序
list_number
=
[
1
,
2
,
3
,
4
,
5
]
random.shuffle(list_number)
print
(
"shuffle(list):"
, list_number)
# 从指定序列中随机获取指定长度的片断
print
(
"sample(sequence):"
, random.sample(
'abcdefg'
,
2
))
运行结果如下
random():
0.6708362810735843
randint(
1000
,
9999
):
5228
randrange(
0
,
21
,
2
):
6
uniform(
0
,
20
):
12.767906137387294
choice(
list
): a
choice(string): d
shuffle(
list
): [
1
,
3
,
5
,
2
,
4
]
sample(sequence): [
'f'
,
'g'
]