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

为何在另一个函数内调用draw函数时返回列表而非字典?

问题原因与解决办法

问题根源

你的draw函数存在返回类型不一致的问题:

  • 当num <= len(self.contents)时,返回统计好的字典drawn_dict
  • 当num > len(self.contents)时,直接返回了列表self.contents

加上draw函数里用self.contents.pop()修改了原对象的内容,直接调用hat.draw(5)之后,hat.contents里的元素已经被移除了一部分。等进入experiment函数再调用hat.draw(num_balls_drawn)时,此时num_balls_drawn很可能大于剩下的元素数量,触发了返回列表的分支,所以你看到的是列表而不是字典。

修复方案

修改draw函数,确保无论哪种情况都返回字典类型:

基础实现版本

def draw(self, num: int) -> dict:
    drawn_dict = {}
    # 取实际能抽取的数量,不超过剩余元素数
    actual_draw = min(num, len(self.contents))
    while actual_draw >= 1:
        drawn_num = self.contents.pop(random.randint(0, len(self.contents) - 1))
        drawn_dict.setdefault(drawn_num, 0)
        drawn_dict[drawn_num] += 1
        actual_draw -= 1
    # 如果num超过剩余数量,把剩下的元素也统计进去并清空原列表
    for item in self.contents:
        drawn_dict.setdefault(item, 0)
        drawn_dict[item] += 1
    self.contents.clear()
    return drawn_dict

用Counter简化的版本

from collections import Counter

def draw(self, num: int) -> dict:
    drawn = []
    actual_draw = min(num, len(self.contents))
    for _ in range(actual_draw):
        idx = random.randint(0, len(self.contents)-1)
        drawn.append(self.contents.pop(idx))
    # 处理超过剩余数量的情况,把剩下的元素全部加入结果并清空原列表
    if num > actual_draw:
        drawn.extend(self.contents)
        self.contents.clear()
    return dict(Counter(drawn))

这样无论num是否超过剩余元素数量,draw函数都会返回字典类型,同时保证操作后contents的状态符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 08:40:24