首页 > 解决方案 > 在 Python 中组合 2 个代码

问题描述

我已经生成了这两个代码。

第一个根据每个国家的客户数量给出的概率生成一个国家:

import random
selectp = random.choices(
        population=["A", "B", "C", "D", "E"],
    weights=[0.2307, 0.0769, 0.3846, 0.1923, 0.1153],
    k=1
)
print(selectp)

第二个通过在适当的地方用零填充左侧的数字来生成 4 个字符的随机数:

import random
num = random.randrange(1, 9999)
# using string's zfill
num_with_zeros = str(num).zfill(4)
print (num_with_zeros)

我需要做的是组合这些代码以生成以下类型的结果,例如以随机方式:

A-0213, B-2345, A-0001...

增加的复杂性是每个字母都有有限数量的组合,它们是:

知道怎么做吗?


编辑:

所以我需要的是一个随机生成类型组合的代码:

A-0001、B-0035...

请记住,字母的概率分布是:

并且该数字必须介于以下数字之间:

标签: python

解决方案


您将需要一个字典来存储允许的数字是什么,然后您可以简单地添加到字符串中+

import random

max_vals = {"A": 300, "B": 100, "C": 500, "D": 250, "E": 150}

def random_code():
    letter = random.choices(list(max_vals.keys()),
                            weights=[0.2307, 0.0769, 0.3846, 0.1923, 0.1153],
    k=1)[0]
    num = random.randrange(0, max_vals[letter]) # You allow 0000 in the examples in the question
    # using string's zfill
    num_with_zeros = str(num).zfill(4)
    return letter + "-" + num_with_zeros

for _ in range(10):
    print(random_code())

推荐阅读