python - 在 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,数字将从 A-0000 变为 A-0300
- 对于 B,数字将从 B-0000 变为 B-0100
- 对于 C,数字将从 C-0000 变为 C-0500
- 对于 D,数字将从 D-0000 变为 D-0250
- 对于 E,数字将从 E-0000 变为 E-0150
知道怎么做吗?
编辑:
所以我需要的是一个随机生成类型组合的代码:
A-0001、B-0035...
请记住,字母的概率分布是:
- A = 0.2307
- B = 0.0769
- C = 0.3846
- D = 0.1923
- E = 0.1153
并且该数字必须介于以下数字之间:
- 对于 A,数字将从 A-0000 变为 A-0300
- 对于 B,数字将从 B-0000 变为 B-0100
- 对于 C,数字将从 C-0000 变为 C-0500
- 对于 D,数字将从 D-0000 变为 D-0250
- 对于 E,数字将从 E-0000 变为 E-0150
解决方案
您将需要一个字典来存储允许的数字是什么,然后您可以简单地添加到字符串中+
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())
推荐阅读
- azure-ad-graph-api - 图形 RBAC 凭证返回错误
- android - 如何添加多个权限?一份来自清单,一份来自运行时
- javascript - 反应上下文提供者 - 不能将调度作为函数传递
- python - multiprocessing.Pool:类实例和泡菜错误
- java - 从多个线程访问 OkHttpClient 响应
- kotlin - 有什么方法可以更改 Kotlin when 语句,以便更有效地包含枚举?
- mysql - 使用用户名而不是 id 从 2 个表中检索数据
- javascript - 替换组件WillMount()
- javascript - 使用正则表达式解析 Markdown 的子集
- bitbucket - bitbucket 是否将 git 归咎于类似于 github 的行功能?