Python 代码解析:统计在线教育投资数据并分析轮次平均金额
import json
with open('data.json', 'r', encoding='utf-8') as f: data = json.load(f)
转换金额单位为人民币
for item in data: if item['投资金额'] != '未披露': if '美元' in item['投资金额']: amount = float(item['投资金额'].replace('美元', '')) * 6.9 item['投资金额'] = str(round(amount, 2)) + ' 人民币' elif '万' in item['投资金额']: amount = float(item['投资金额'].replace('万', '')) * 10000 item['投资金额'] = str(int(amount)) + ' 人民币' else: item['投资金额'] = item['投资金额'] + ' 人民币' else: item['投资金额'] = '0 人民币'
统计各轮次平均投资金额
rounds = {} for item in data: if item['融资轮次'] not in rounds: rounds[item['融资轮次']] = {'总金额': 0, '投资次数': 0} rounds[item['融资轮次']]['总金额'] += float(item['投资金额'].replace(' 人民币', '')) rounds[item['融资轮次']]['投资次数'] += 1
for k in rounds: rounds[k]['平均投资金额'] = rounds[k]['总金额'] / rounds[k]['投资次数']
按照金额降序输出,金额相同按照轮次升序
result = sorted(rounds.items(), key=lambda x: (-x[1]['平均投资金额'], x[0]))
将结果写入result.txt文件中
with open('result.txt', 'w', encoding='utf-8') as f: for item in result: f.write(f"{item[0]}: {round(item[1]['平均投资金额'], 2)} 人民币\n")
原文地址: https://www.cveoy.top/t/topic/oiZs 著作权归作者所有。请勿转载和采集!