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

Python构建嵌套字典时重复值未保存问题求助

问题分析与解决

错误原因

你代码里的核心问题出在strlist.index(n)这个调用上:

  • list.index()方法的特性是返回第一个匹配元素的索引,而不是当前循环到的元素的真实索引。
  • 当循环处理第二个"11"时,strlist.index("11")返回的还是第一个"11"的位置1,而非当前的索引2。这就导致你给weighted_dict[1]重复赋值(虽然值看起来一致),本该生成的键2根本没被创建,最终结果里就少了索引2对应的条目。

修正方案

改用enumerate()函数,它能在循环时同时拿到当前元素的真实索引和元素值,完美解决这个问题:

def order_weight(strng):
    strlist = strng.split(' ')
    weighted_dict = {}
    # 用enumerate获取索引和元素
    for idx, n in enumerate(strlist):
        digtotal = 0
        for digit in n:
            digtotal += int(digit)
        weighted_dict[idx] = {digtotal: n}
    print(weighted_dict)

order_weight("9999 11 11 22")

运行结果

修正后执行代码,输出就是你预期的结果:
{0: {36: '9999'}, 1: {2: '11'}, 2: {2: '11'}, 3: {4: '22'}}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 14:46:02