random模块
一、常用方法
import random
-
大于0且小于1之间的小数[0,1)
print(random.random())0.42866657593385415
-
大于等于1且小于等于3之间的整数
print(random.randint(1, 3))3
-
打乱l的顺序,相当于"洗牌"
lis = [1, 3, 5, 7, 9] random.shuffle(lis) print(lis)[9, 1, 5, 7, 3]
二、不常用方法
-
大于等于1且小于3之间的整数
print(random.randrange(1, 3)) -
列表内的任意一个元素,即1或者‘23’或者[4,5]
print(random.choice([1, '23', [4, 5]])) -
列表元素任意n个元素的组合,示例n=2
# random.sample([], n),列表元素任意n个元素的组合,示例n=2 print(random.sample([1, '23', [4, 5]], 2)) -
大于1小于3的小数
print(random.uniform(1, 3))2.1789596280319605
三、获取随机数
import random
def random_code(n):
num_code = ""
while n > 0:
num = random.randint(48, 122)
if 57 < num < 65 or 90 < num < 97:
continue
num_code += chr(num)
n -= 1
return num_code
res_code = random_code(5)
print(res_code)
四、总结
- random:0-1的随机数
- randint:0-100(包含)的整数
- shuffle:打乱容器类元素
- randrange:1,9之内的整数
- uniform:1-3的小数
- choice:选一个
- sample:选n个