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

random.choice返回不存在的键?我的Python代码哪里出错了?

问题分析与解决

不是random.choice出问题了,问题出在你向列表添加元素的方式上。

错误原因

你的cards字典里包含'10'这个键,当random.choice选中'10'时,你用了dealt_cards += random.choice(...)的写法——字符串是可迭代对象,+=会把字符串拆成单个字符逐个添加到列表里,所以'10'会被拆成'1'和'0'两个元素。这就是你看到列表里出现'1'、'0',以及调用random_cards(4)却得到5个元素的原因。

修正方法

有两种方式可以解决这个问题:

  • 使用list.append()方法直接添加整个元素:
import random

cards = {'A': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '10': 10, 'J': 10, 'Q': 10, 'K': 10}

def random_cards(n):
    dealt_cards = []
    for i in range(n):
        dealt_cards.append(random.choice(list(cards.keys())))
    print(dealt_cards)
  • 或者把选中的元素放到列表中再进行拼接,避免字符串被拆分:
import random

cards = {'A': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '10': 10, 'J': 10, 'Q': 10, 'K': 10}

def random_cards(n):
    dealt_cards = []
    for i in range(n):
        dealt_cards += [random.choice(list(cards.keys()))]
    print(dealt_cards)

修正后效果示例

调用random_cards(4)会得到类似这样的随机结果:

['A', '10', '3', 'J']

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 07:15:42