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

Python中将列表转换为字典并为每个键分配随机取值的实现方法

问题根源

你现在的代码出现所有值相同的问题主要有两个原因:

  • dict.fromkeys()的第二个参数是固定值,只会计算一次,不会为每个键单独调用random.choice()生成新随机值
  • 你把字典的生成逻辑放在了循环内部,每轮循环都会覆盖已生成的字典,属于冗余逻辑

解决方法

最简单的实现是用字典推导式,代码更简洁,也能保证每个键对应的值都是独立随机生成的:

import random

choices = ["Rock", "Paper", "Scissors"]
number_of_players = 5

# 字典推导式直接生成结果
players_dictionary = {
    f"P{i}": random.choice(choices) 
    for i in range(1, number_of_players + 1)
}

print(players_dictionary)

如果你习惯用普通循环实现,也可以参考以下写法:

import random

players_dictionary = {}
choices = ["Rock", "Paper", "Scissors"]
number_of_players = 5

for i in range(1, number_of_players + 1):
    player_key = f"P{i}"
    # 每次循环单独生成随机值
    players_dictionary[player_key] = random.choice(choices)

print(players_dictionary)

运行示例

以玩家数量为5为例,运行后输出结果类似:

{'P1': 'Scissors', 'P2': 'Rock', 'P3': 'Paper', 'P4': 'Rock', 'P5': 'Scissors'}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 05:09:01