You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python以随机姓名为key生成字典时条目数不符合预期问题

问题原因

Python字典的键具有唯一性,你在循环中通过random.choice(self.nombres)随机选取姓名作为键,一旦重复抽到同一个姓名,后续的赋值操作只会覆盖该键已有的值,不会新增字典条目,所以最终字典的条目数会小于你设定的numero_usuarios。

解决方案

根据你的使用场景二选一即可:

场景1:要求生成的用户姓名不重复

使用random.sample()方法从姓名列表中一次性抽取指定数量的不重复姓名,再逐个分配随机优先级即可。注意抽取的用户数量不能超过预置姓名列表的总长度:

def generar_diccionario_usuarios(self, numero_usuarios : int):
    # 校验参数合法性
    if numero_usuarios > len(self.nombres):
        raise ValueError(f"预置姓名总数为{len(self.nombres)},无法生成更多不重复用户")
    # 清空历史数据,避免多次调用时数据叠加
    self.usuarios = {}
    # 抽取不重复姓名
    selected_names = random.sample(self.nombres, numero_usuarios)
    for name in selected_names:
        self.usuarios[name] = random.randint(1, 10)
    print(self.usuarios)

场景2:允许存在重名用户

不要使用姓名作为字典键,改用自增序号作为键,值存储姓名和优先级的组合即可:

def generar_diccionario_usuarios(self, numero_usuarios : int):
    self.usuarios = {}
    for i in range(numero_usuarios):
        name = random.choice(self.nombres)
        priority = random.randint(1, 10)
        self.usuarios[i] = (name, priority)
    print(self.usuarios)

内容的提问来源于stack exchange,提问作者Mario Almaguer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 17:45:04