Python 处理 JSON 数据集:统计在线教育投资轮次平均金额
import json
读取json文件
with open('data.json', 'r', encoding='utf-8') as f: data = json.load(f)
统计各轮次的投资金额
rounds = {} # 轮次:[金额列表] for item in data: round = item['融资轮次'] amount = item['投资金额'] if amount == '未披露': amount = 0 elif '万' in amount: amount = float(amount.strip('万')) * 10000 elif '亿' in amount: amount = float(amount.strip('亿')) * 100000000 else: amount = float(amount) if round in rounds: rounds[round].append(amount) else: rounds[round] = [amount]
计算各轮次平均投资金额
average_amounts = {} # 轮次:平均金额 for round in rounds: average_amounts[round] = sum(rounds[round]) / len(rounds[round])
按照金额降序、轮次升序排序
sorted_rounds = sorted(average_amounts.items(), key=lambda x: (-x[1], x[0]))
写入result.txt文件
with open('result.txt', 'w', encoding='utf-8') as f: for round, amount in sorted_rounds: f.write(f'{round}: {amount:.2f}\n')
原文地址: http://www.cveoy.top/t/topic/oiZn 著作权归作者所有。请勿转载和采集!