python3 randomModule.py

"""
模块:python3 randomModule.py
功能:python3 random 模块。
参考:https://www.runoob.com/python3/python3-func-number-random.html
知识点:
1.random.random() -> [0,1)范围内的随机浮点数。

2.random.uniform(a, b)
    根据四舍五入,在[a,b)或[a,b]范围内得到一个随机浮点数。
    个人认为:在[a,b)范围内的随机浮点数。

3.random.randint(a, b)
    返回范围 [a,b] 中的随机整数,包括两个端点。

4.random.sample(population, k) -> [sample1,sample2, ..., sampleK]
    从 population 序列或集合中,选择 k 个唯一的随机元素。

    返回一个新的列表,其中包含来自 population 的元素,同时保持原始 population 不变。
    结果列表是按选择顺序排列的,因此所有子切片也将是有效的随机样本。
    这允许抽奖获奖者(样本)被划分为大奖和第二名获奖者(切片)。

    population 的成员不需要是可散列的或唯一的。
    如果 population 包含重复,则每个发生都是样本中的可能选择。

    若要在整数范围内选择样本,请使用 range 作为参数。
    这对于从大量 population 中取样特别快和空间高效:random.sample(range(10000000), 60)
"""
import random

# 1.random.random() -> [0,1)范围内的随机数。
print(random.random())
# 0.3376466882363772

# 2.random.uniform(a, b) -> [a,b)范围内的随机浮点数。
# 获取[1, 10) 范围内的随机浮点数。
print("\n2.")
print(random.uniform(1, 10))
# 4.6064898295249765

# 3.获取一个随机整数。
# 获取 [1, 100] 中的随机整数。
print("\n3.")
print(random.randint(1, 100))
# 45


# 4. 随机取样。
# 4.1.从列表中随机取样,2 个元素。
print("\n4.1.")
lis = [1, 3, 5, 7, 9]
samples = random.sample(lis, 2)
print("samples:", samples)
# samples: [9, 3]

# 4.2.从字典中随机取样。
print("\n4.2.")
dictB = {1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7'}
dictA = {1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7'}

for c in dictB.keys():
    a = random.sample(dictA.keys(), 1)  # 随机一个字典中的key,第二个参数为限制个数
    b = a[0]
    print(dictA[b])  # 打印随机抽取的值
    del dictA[b]  # 删除已抽取的键值对
    print(dictA)  # 打印剩余的键值对
# 4
# {1: '1', 2: '2', 3: '3', 5: '5', 6: '6', 7: '7'}
# 7
# {1: '1', 2: '2', 3: '3', 5: '5', 6: '6'}
# 1
# {2: '2', 3: '3', 5: '5', 6: '6'}
# 3
# {2: '2', 5: '5', 6: '6'}
# 2
# {5: '5', 6: '6'}
# 5
# {6: '6'}
# 6
# {}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值