python3 random模块

import random


'''random随机数模块'''
# 生成一个0到1的随机小数,不常用
print(random.random())
print(type(random.random()))
0.591104288833299
<class 'float'>

import random

# randint(start, end)生成一个随机整数,[start, end]包括头和尾
print(random.randint(10, 12))
print(type(random.randint(10, 12)))
12
<class 'int'>

import random

# uniform(start, end)生成一个随机小数,常用
print(random.uniform(10, 20))
print(type(random.uniform(10, 20)))
15.941228671334322
<class 'float'>

# 保留2位小数
f2 = format(3.1415926, ".2f")
print(f2)
print(type(f2))

# 转化为浮点数
f3 = float(f2)
print(f3)
print(type(f3))
3.14
<class 'str'>
3.14
<class 'float'>

import random

# choice随机从可迭代对象中,选择一个
lst = [4, 1, 3]
print(random.choice(lst))
4

import random

# sample从可迭代对象中随机拿到n个数据,返回一个列表
lst = [1, 3, 5, 6, 9]
print(random.sample(lst, 2))

# sample 样品
[5, 9]

import random


# 大小写字母列表
lst = list(map(lambda x: chr(x), set(range(65, 91)) | set(range(97, 123))))
# 包括数字
lst.extend(range(10))
print(lst)
# sample随机从可迭代对象中选择n个元素, 返回一个列表
print(random.sample(lst, 4))
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
['y', 's', 'U', 'e']

import random

# 从数字和大小写字母中随机产生4位验证码
# 有简单表示大小写字母和数字的方法吗? 论简单方法,还是直接写的简单,哈哈^ -^
# s = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
s = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
print("".join(random.sample(s, 4)))
hjKx

import random

# shuffle打乱可迭代对象
lst = ["a", "b", "c", "d"]
random.shuffle(lst)
print(lst)

# shuffle 洗牌
['a', 'c', 'b', 'd']

import random

'''做练习:从1到36个数中,随机生成7个数,禁止使用sample【集合去重的使用】'''
s = set()
while len(s) <= 7:
    s.add(random.randint(1, 36))
print(s)
{5, 7, 9, 11, 17, 19, 24, 29}
原文地址:https://www.cnblogs.com/lilyxiaoyy/p/10789993.html