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

Python计算三维列表中各颜色总和及元素占比问题求助

修正代码实现颜色总和与占比计算

我有一个包含字符串和数字的三维列表,需要计算每种颜色的总和,以及每个元素对对应颜色总和的占比。

原代码

from collections import defaultdict

d = defaultdict(int)
dc = defaultdict(int) 

l = [('red', 'apple', 7), ('red', 'car', 4), ('red', 'shoe', 3), ('blue', 'candy', 4), ('blue', 'bike', 5), ('green', 'melon', 2)]

for color, name, number in l:
    d[color] += number
    total = str(d)
    
    for color, name, number in l:
        dc[color] /= number
        percent = str(dc)

print(total, percent)

当前输出

defaultdict(<class 'int'>, {'red': 14, 'blue': 9, 'green': 2}) defaultdict(<class 'int'>, {'red': 0.0, 'blue': 0.0, 'green': 0.0})

期望输出

red: 14
blue: 9
green: 2

red apple: 7/14 = 50%
red car: 4/14 = 29%
red shoe: 3/14 = 21%
blue candy: 4/9 = 44%
blue bike: 5/9 = 56%

修正后的代码

from collections import defaultdict

# 计算每种颜色的总和
color_totals = defaultdict(int)
items = [('red', 'apple', 7), ('red', 'car', 4), ('red', 'shoe', 3), ('blue', 'candy', 4), ('blue', 'bike', 5), ('green', 'melon', 2)]

for color, _, num in items:
    color_totals[color] += num

# 输出颜色总和
for color, total in color_totals.items():
    print(f"{color}: {total}")
print()  # 空行分隔

# 计算并输出每个元素的占比
for color, name, num in items:
    total = color_totals[color]
    percentage = round((num / total) * 100)
    print(f"{color} {name}: {num}/{total} = {percentage}%")

修正说明

原代码存在两个核心问题:

  1. 嵌套循环重复遍历列表,导致占比计算逻辑混乱;
  2. 占比计算方式错误,dc[color] /= number会不断用当前值除以元素数值,最终结果趋近于0。

修正逻辑:

  1. 先单独遍历一次列表,统计每种颜色的总和,存储在字典中;
  2. 遍历总和字典,输出每种颜色的总数值;
  3. 再次遍历原列表,用每个元素的数值除以对应颜色的总和,计算百分比并格式化输出,通过round()取整匹配期望的整数百分比格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 18:25:39