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

如何实现统计列表中相同id和star的字典并正确更新id_count?

问题:统计相同id和star的字典数量并更新计数

需求:统计all_list中拥有相同id和star的字典数量,若id_count列表中无对应id和star的字典,则将其添加到id_count中。

现有代码

id_count = [{'id': 33, 'star': 2, 'count': 3}]

all_list = [{'power': 20710, 'id': 33, 'skills': "", 'rank': 0, 'lv': 1, 'star': 2},
            {'power': 22296, 'id': 49, 'skills': "", 'rank': 0, 'lv': 1, 'star': 2},
            {'power': 25029, 'id': 53, 'skills': "", 'rank': 0, 'lv': 1, 'star': 3}]

for single_partner_info in all_list:
    for each in id_count:
        if ("id", single_partner_info["id"]) in each.items():
            if  ("star", single_partner_info["star"]) in each.items():
                each["count"] +=1
        else:
            id_count.append(dict(id=single_partner_info["id"],
                                star=single_partner_info["star"],
                                    count=1))

print(id_count)

运行结果

[{'id': 33, 'star': 2, 'count': 3}, 
{'id': 49, 'star': 2, 'count': 2}, 
{'id': 53, 'star': 3, 'count': 2}, 
{'id': 53, 'star': 3, 'count': 2}]

期望结果

[{'id': 33, 'star': 2, 'count': 4}, 
{'id': 49, 'star': 2, 'count': 1}, 
{'id': 53, 'star': 3, 'count': 1}]

问题分析

  • 嵌套循环逻辑错误:遍历id_count时,只要当前元素不匹配就执行添加操作,导致同一个条目被重复添加多次。
  • 判断条件冗余:用("id", 值) in each.items()的写法既不直观,也容易引发逻辑漏洞。
  • 缺少匹配标记:没有记录是否找到对应条目,匹配成功后仍可能触发后续的添加逻辑。

修改后的代码

id_count = [{'id': 33, 'star': 2, 'count': 3}]

all_list = [{'power': 20710, 'id': 33, 'skills': "", 'rank': 0, 'lv': 1, 'star': 2},
            {'power': 22296, 'id': 49, 'skills': "", 'rank': 0, 'lv': 1, 'star': 2},
            {'power': 25029, 'id': 53, 'skills': "", 'rank': 0, 'lv': 1, 'star': 3}]

for single in all_list:
    current_id = single['id']
    current_star = single['star']
    found_match = False
    
    # 遍历id_count查找匹配的id和star组合
    for item in id_count:
        if item['id'] == current_id and item['star'] == current_star:
            item['count'] += 1
            found_match = True
            break  # 找到匹配项后立即跳出循环,避免无效遍历
    
    # 未找到匹配项时,添加新的计数条目
    if not found_match:
        id_count.append({'id': current_id, 'star': current_star, 'count': 1})

print(id_count)

代码说明

  • 新增found_match标记,精准记录是否找到对应条目,避免重复添加。
  • 直接通过键取值比较id和star,逻辑简洁清晰。
  • 找到匹配项后立即终止内层循环,提升代码执行效率。
  • 仅在遍历完所有id_count元素都无匹配时,才执行添加操作,确保结果准确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 06:05:00