python - dict列表中的值总和错误
问题描述
从带有字典列表的 JSON 文件中,我试图获取每个用户的数据并使用它们来创建新的字典。由于每个用户都有多个对象,因此我使用 for 循环通过它们进行交互。开始 json 看起来像这样:
[{
"obj_id": "bfyguwc9971",
"user_id": 3,
"investment": 34,
"profit": 67
},
{
"obj_id": "sdklgnv820",
"user_id": 12,
"investment": 71,
"profit": 43
}]
JSON 包含数百个这样的字典,我想要实现的是最终的字典,其中包含每个用户的平均投资和利润。这是我正在运行的代码:
import json
with open('user_data.json','r') as f:
user_data = json.load(f)
users_id = []
users_dict = {}
obj_count = 0
investment_list = []
profit_list = []
for i in user_data:
if i['user_id'] not in users_id:
users_id.append(i['user_id'])
for a in users_id:
users_dict[a] = {}
for i in user_data:
if i['user_id'] == a:
obj_count += 1
users_dict[a]['Objects'] = obj_count
investment_list.append(i['investment'])
profit_list.append(i['profit'])
avg_investment = (sum(investment_list)/len(investment_list))
users_dict[a]['avg_investment'] = avg_investment
avg_profit = (sum(profit_list)/len(profit_list))
users_dict[a]['avg_profit'] = avg_profit
print(users_dict)
问题出现在输出中,而不是给我每个用户正确的单个值,它给了我第一个用户值的权利,然后它继续为下一个用户添加值,所以最后一个用户将拥有所有以前的值为其他用户计算。我究竟做错了什么?提前感谢您帮助我!
解决方案
推荐阅读
- css - 如何像普通 HTML 文本或任何其他文本编辑器一样光标选择 SVG/d3.js 文本?
- css - 三星上网匹配 justify-content: space-evenly 但不支持
- c# - Grid 设置了 PreviewMouseMove 时 WPF 按钮事件未触发
- regex - Javacc 正则表达式跳过所有字符,除非找到特定字符
- python - 解析 HTML 时遇到问题
- r - 无法将数据存储在矩阵中
- javascript - 图像未在 pdf jspdf 中显示
- google-bigquery - 如何在 Biquery 中使用 param.key 值“action”和“label”在两个不同的列中创建报告
- angular - 我在 chrome 中收到错误,因为 400 bad request for preflight。Angular + Azure 函数
- localhost - 如何解决 - ORO-CRM 中的“拒绝在框架中显示,因为它将 X-Frame-Options 设置为同源”