码迷,mamicode.com
首页 > 其他好文 > 详细

29 random模块

时间:2018-07-02 14:50:28      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:.sh   使用   auto   AC   mon   hit   随机   cell   ons   

# 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]

 

# random各种使用方法
import random
 
# 随机生成[0.1)的浮点数
print("random():", random.random())
 
# 随机生成1000-9999之间的整数
print("randint(1000, 9999):", random.randint(10009999))
 
# 随机生成0-20之间的偶数
print("randrange(0, 21, 2):", random.randrange(0212))
 
# 随机生成0-20之间的浮点数
print("uniform(0, 20):", random.uniform(020))
 
# 从序列中随机选择一个元素
list_string = [‘a‘‘b‘‘c‘‘d‘‘e‘]
print("choice(list):", random.choice(list_string))
print("choice(string):", random.choice(‘abcd‘))
 
# 对列表元素随机排序
list_number = [12345]
random.shuffle(list_number)
print("shuffle(list):", list_number)
 
# 从指定序列中随机获取指定长度的片断
print("sample(sequence):", random.sample(‘abcdefg‘2))

 运行结果:

1
2
3
4
5
6
7
8
random(): 0.6708362810735843
randint(10009999): 5228
randrange(0212): 6
uniform(020): 12.767906137387294
choice(list): a
choice(string): d
shuffle(list): [13524]
sample(sequence): [‘f‘‘g‘]

29 random模块

标签:.sh   使用   auto   AC   mon   hit   随机   cell   ons   

原文地址:https://www.cnblogs.com/jeavy/p/9253586.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!