1-Python之random模块

前言

该模块实现了各种分布的伪随机数生成器。我们可以用该模块生成随机数或者字符串。

常用方法

  • random.random(),返回0~1之间的随机浮点数据。
import random
print(random.random())  # 0.4390372412981508
  • random.sample(Population, k),从指定范围内(Population)返回指定个数(k)的不重复的元素,注意,从Python3.9开始Population必须是有序类型,这就意味着set和dict将不能作为Population了,必须sorted排序之后或者转为list或者元组才能使用。官网:https://docs.python.org/zh-cn/3.9/library/random.html#module-random
import random
print(random.sample(range(100), 5))  # [19, 8, 96, 70, 88]
print(random.sample([1, 2, 3, 4, 5, 6], 3))  # [3, 1, 5]
print(random.sample(['a', 'b', 'c', 'd', 'e'], 3))  # ['a', 'd', 'c']
print(random.sample('abcde', 3))  # ['a', 'c', 'e']
print(random.sample({'a': 1, 'b': 2, 'c': 3}, 2))   # TypeError: Population must be a sequence or set.  For dicts, use list(d).
print(random.sample((1, 2, 3, 4), 2))  # [1, 3]

# 遇到这个提示不要慌:
print(random.sample({1, 2, 3, 4, 5}, 1))
"""
# 下面这个warning说得还是集合不能作为Population使用了。
DeprecationWarning: Sampling from a set deprecated
since Python 3.9 and will be removed in a subsequent version.
  random.sample({1, 2, 3, 4, 5}, 1)
"""


  • random.randint(a, b),返回a~b中的整数,包括a和b本身。
import random
print(random.randint(1, 10))  # 1
print(random.randint(1, 1))  # 1
print(random.randint(1.1, 10.5))   # ValueError: non-integer arg 1 for randrange()
  • random.choice(seq),从seq中返回其中一个值。
import random
print(random.choice(range(100)))  # 1
  • random.randrange(),从start ~ stop之间(包含本身)返回一个随机数,并可以指定步长step
import random
print(random.randrange(start=1, stop=4, step=1))  # 会在1,2,3,4中随机返回一个
print(random.randrange(start=1, stop=4, step=2))  # 从每隔两个中随机会返回1个随机数,也就是说从1,3中返回
  • random.shuffle(seq),打乱指定的seq。需要注意的是该方法没有返回值,只是将在原seq的序列顺序打乱。
import random
l = list(range(1, 20))
random.shuffle(l)
print(l)  # [19, 11, 12, 17, 6, 3, 9, 5, 18, 13, 2, 16, 10, 15, 1, 4, 7, 8, 14]

应用示例

验证码

生成一个6位随机验证码(包含数字和大小写字母)。

import random
def verification_code():
    code = ''
    for i in range(6):
        num = random.randint(0, 9)  # 随机整数
        alf_big = chr(random.randint(65, 90))   # 随机大写的A-Z
        alf_small = chr(random.randint(97, 122))    # 随机小的a-z
        add = random.choice([num, alf_big, alf_small])
        code += str(add)
    return code
print(verification_code())     # P452t4

发红包

发红包、指定金额和个数,并随机分配红包金额。

  • 发红包1.0版 200块钱 10个红包
import random
r = random.sample(range(1, 200), 9)
r.sort()
r.insert(0, 0)
r.append(200)
# print(r)  # [0, 34, 60, 80, 88, 97, 101, 125, 171, 180, 200]
l = []
for i in range(10):
    l.append((r[i + 1] - r[i]))
print(l, abs(sum(l)))  # [34, 26, 20, 8, 9, 4, 24, 46, 9, 20] 200
  • 红包2.0版
import random
def red_lv1(money, num):
    r = random.sample(range(1, money * 100), num - 1)
    r.sort()
    r.append(money * 100)
    r.insert(0, 0)
    l = []
    for i in range(num):
        l.append((r[i + 1] - r[i]) / 100)
    return l
print(red_lv1(200, 10))  # [5.01, 36.25, 5.94, 35.62, 4.96, 0.07, 56.16, 11.68, 3.92, 40.39]
  • 红包3.0版
import random
def red_lv2(money, num):
    r = random.sample(range(1, money * 100), num - 1)
    r.sort()
    r.append(money * 100)
    r.insert(0, 0)
    return [(r[i + 1] - r[i]) / 100 for i in range(num)]
print(red_lv2(200, 10))  # [0.61, 74.34, 10.32, 52.56, 0.36, 23.64, 1.01, 29.84, 2.45, 4.87]
  • 红包4.0版
import random
def red_lv3(money, num):
    r = random.sample(range(1, money * 100), num - 1)
    r.extend([0, money * 100])
    r.sort()
    return [(r[i + 1] - r[i]) / 100 for i in range(num)]
print(red_lv3(200, 10))  # [8.99, 1.19, 6.68, 8.5, 15.29, 34.54, 88.79, 3.58, 28.95, 3.49]
  • 红包5.0 生成器版
import random
def red_lv_g(money, num):
    r = random.sample(range(1, money * 100), num - 1)
    r.extend([0, money * 100])
    r.sort()
    for i in range(num):
        yield (r[i + 1] - r[i]) / 100
print(list(red_lv_g(200, 10)))  # [46.4, 2.17, 1.57, 3.08, 2.84, 22.74, 13.01, 89.63, 12.17, 6.39]
import random
from time import sleep

# 所有涉及金额的浮点数都需要用 round 方法保留2位小数,避免出现最终结果多出0.01
amount = round(float(input('请设置红包的金额 \> ')), 2)
num = int(input('请设置红包的数量 \> '))
hb_dict = {}
xing = '赵钱孙李周吴郑王'
ming = '一二三四五六七八九十'

while num:

    xingming = random.choice(xing) + random.choice(ming) + random.choice(ming)
    if xingming in hb_dict.keys():
        xingming = random.choice(xing) + random.choice(ming) + random.choice(ming)

    num -= 1
    if num == 0:
        print('%s抢到红包%.2f元 红包抢完了!' % (xingming, amount))
        hb_dict[amount] = xingming
        amount -= amount
    elif num > 0:
        hb = round(random.uniform(0.01, amount) / num, 2)
        hb_dict[hb] = xingming
        # 算法: 在0.01到红包总金额之间随机一个浮点数 / 红包剩余个数
        print('%s抢到红包%.2f元 剩余%d个!' % (xingming, hb, num))
        amount = round((amount - hb), 2)

    sleep(1)

# 转置字典中的 key / value
# hb_dict2 = {value:key for key,value in hb_dict.items()}
max_hb = max(hb_dict.items())
print('%s运气最佳 抢得%.2f元!!' % (max_hb[1], max_hb[0]))
'''结果如下:
请设置红包的金额 \> 200
请设置红包的数量 \> 10
李四二抢到红包3.07元 剩余9个!
赵七一抢到红包19.44元 剩余8个!
王一九抢到红包23.82元 剩余7个!
李三七抢到红包16.08元 剩余6个!
周十二抢到红包15.65元 剩余5个!
孙六一抢到红包7.56元 剩余4个!
郑九二抢到红包18.61元 剩余3个!
钱一四抢到红包34.25元 剩余2个!
李九三抢到红包28.05元 剩余1个!
李七三抢到红包33.47元 红包抢完了!
钱一四运气最佳 抢得34.25元!!
'''

欢迎斧正,that's all see also:[random --- 生成伪随机数](https://docs.python.org/zh-cn/3.8/library/random.html) | [Python random模块](https://my.oschina.net/cuffica/blog/33336)
posted @ 2019-06-07 15:11  听雨危楼  阅读(897)  评论(0编辑  收藏  举报