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

如何在Python中不依赖第三方库按营收降序写入CSV文件

问题描述

现有两个业务字典:

  • 产品基础信息字典 ProductMaster:
ProductMaster = { 
    1 : ["Minor Widget",0.25,250],
    2 : ["Critical Widget",5.00,10],
    3 : ["Complete System (Basic)",500,1],
    4 : ["Complete System (Deluxe)",625,1]
}
  • 产品营收统计字典 productReport:
productReport = { 
    1 : [687500.0,11000,0.0],
    2 : [250000.0,5000,12500.0],
    3 : [1500000.0,3000,92500.0],
    4 : [0,0,0]
}

其中productReport的列表值第一个元素为营收(GrossRevenue)。需要基于这两个字典生成CSV文件,并按营收降序排列。

现有代码生成的CSV未按要求排序,当前输出:

Name,GrossRevenue,TotalUnits,DiscountCost
Minor Widget,687500.0,11000,0.0
Critical Widget,250000.0,5000,12500.0
Complete System (Basic),1500000.0,3000,92500.0
Complete System (Deluxe),0,0,0

预期输出:

Name,GrossRevenue,TotalUnits,DiscountCost
Complete System (Basic),1500000.0,3000,92500.0
Minor Widget,687500.0,11000,0.0
Critical Widget,250000.0,5000,12500.0
Complete System (Deluxe),0,0,0

要求:不使用pandas等第三方库实现。

解决方案

核心思路是先收集所有待写入的数据行,再按营收字段降序排序,最后写入文件。修改后的代码如下:

import csv

ProductReport_Filename = "product_report.csv"  # 替换为你的目标文件名

# 原业务字典(可根据实际场景读取,此处保留示例数据)
ProductMaster = { 
    1 : ["Minor Widget",0.25,250],
    2 : ["Critical Widget",5.00,10],
    3 : ["Complete System (Basic)",500,1],
    4 : ["Complete System (Deluxe)",625,1]
}

productReport = { 
    1 : [687500.0,11000,0.0],
    2 : [250000.0,5000,12500.0],
    3 : [1500000.0,3000,92500.0],
    4 : [0,0,0]
}

with open(ProductReport_Filename, 'w') as file:
    csvWriter = csv.writer(file)
    # 写入表头
    csvWriter.writerow(["Name","GrossRevenue","TotalUnits","DiscountCost"])
    
    # 收集所有符合条件的数据行
    rows = []
    productKeys = ProductMaster.keys()
    for key, value in productReport.items():
        if key in productKeys:
            rows.append([ProductMaster[key][0], *value])
    
    # 按营收(每行第2个元素,索引为1)降序排序
    sorted_rows = sorted(rows, key=lambda x: x[1], reverse=True)
    
    # 批量写入排序后的行
    csvWriter.writerows(sorted_rows)

关键说明

  1. 数据收集:先将所有待写入内容存入rows列表,解决原代码边遍历边写入无法排序的问题。
  2. 排序逻辑:通过sorted()函数,用lambda x: x[1]指定按每行的营收字段排序,reverse=True实现降序排列。
  3. 批量写入:使用writerows()一次性写入所有排序后的行,比逐行写入效率更高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 09:02:57