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

如何将含重复产品名的Python嵌套列表按产品汇总金额?

解决Python嵌套列表的产品金额汇总问题

针对你给出的嵌套列表,我们可以用字典来实现金额的累加汇总,这是适合新手理解的基础方法,步骤如下:

实现步骤

  1. 创建一个空字典,用来存储每个产品的累计金额(键是产品名,值是总金额)
  2. 遍历原始嵌套列表中的每一项,拆分出产品名称和对应金额
  3. 对每个产品进行判断:如果产品已在字典中,就把金额加到已有值上;如果不在,就将产品作为新键存入字典,金额作为初始值
  4. 最后把字典转换为要求的嵌套列表格式

代码示例

# 原始数据
products_store = [['Shampoo', 35], ['Soap', 100], ['Soap', 150], ['Towels', 45], ['Shampoo', 55]]

# 初始化空字典用于统计
total_dict = {}

# 遍历原始列表
for item in products_store:
    product_name = item[0]
    price = item[1]
    # 判断产品是否已在字典中
    if product_name in total_dict:
        total_dict[product_name] += price
    else:
        total_dict[product_name] = price

# 把字典转换为嵌套列表格式
result = [[key, value] for key, value in total_dict.items()]

print(result)

运行这段代码后,输出就是你需要的:

[['Shampoo', 90], ['Soap', 250], ['Towels', 45]]

扩展小技巧(可选)

如果之后学到了collections模块,可以用defaultdict简化代码,避免手动判断键是否存在:

from collections import defaultdict

products_store = [['Shampoo', 35], ['Soap', 100], ['Soap', 150], ['Towels', 45], ['Shampoo', 55]]
total_dict = defaultdict(int)

for product_name, price in products_store:
    total_dict[product_name] += price

result = [[key, value] for key, value in total_dict.items()]
print(result)

这个方法更简洁,但基础字典的实现方式更适合刚学编程的阶段理解底层逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 10:50:27