【发布时间】:2020-10-14 01:33:15
【问题描述】:
我有一个 json 文件,其中播放器的结构是这样的
[
{
"Player_Name": "Rory McIlroy",
"Tournament": [
{
"Name": "Arnold Palmer Invitational presented by Mastercard",
"Points": "68.10",
"Salary": "12200.00"
},
{
"Name": "World Golf Championships-Mexico Championship",
"Points": "103.30",
"Salary": "12200.00"
},
{
"Name": "The Genesis Invitational",
"Points": "88.60",
"Salary": "12200.00"
},
{
"Name": "Farmers Insurance Open",
"Points": "107.30",
"Salary": "12200.00"
},
{
"Name": "World Golf Championships-HSBC Champions",
"Points": "138.70",
"Salary": "12400.00"
},
{
"Name": "The ZOZO Championship",
"Points": "103.40",
"Salary": "12300.00"
}
]
}]
当我运行这段代码时
import json
import numpy as np
import pandas as pd
from itertools import groupby
# using json open the player objects file and set it equal to data
with open('Active_PGA_Player_Objects.json') as json_file:
data = json.load(json_file)
with open('Players_DK.json') as json_file:
Players_DK = json.load(json_file)
results = []
for k,g in groupby(sorted(data, key=lambda x:x['Player_Name']), lambda x:x['Player_Name']):
results.append({'Player_Name':k, 'Tournament':[i['Tournament'][0] for i in g]})
for obj in results:
for x in Players_DK:
if obj['Player_Name'] == x['Name']:
obj['Average'] = x['AvgPointsPerGame']
i = 0
points_results = []
while i < len(results):
j = 0
while j < len(results[i]['Tournament']):
difference = (int(float(results[i]['Tournament'][j]['Points'])) - (results[i]['Average']))
points_results.append(round(difference,2))
j += 1
i += 1
with open('PGA_Player_Objects_w_Average.json', 'w') as my_file:
json.dump(results, my_file)
我的列表是这样返回的
[{
"Player_Name": "Rory McIlroy",
"Tournament": [
{
"Name": "Arnold Palmer Invitational presented by Mastercard",
"Points": "68.10",
"Salary": "12200.00"
}
],
"Average": 96.19
}]
有人可以向我解释为什么当我更新特定字典时,它会从嵌套的Tournament 列表中删除除第一个值之外的所有值?我的目标是将每个玩家的平均值添加到他们相应的字典中,以便我可以取每个平均值并从每个分数中减去它。当我尝试执行此操作时,我只能对列表中剩下的一个值执行它。
【问题讨论】:
-
还有关于迭代的建议吗?嵌套循环很恶心。
-
你为什么使用
while循环???无论如何,它总能帮助你解释你的代码应该做什么。 -
@juanpa.arrivillaga 我享受苦难
-
无论如何,这是因为您使用了
[i['Tournament'][0] for i in g]。因此,您只需要获取该列表中的第一项,并且该列表中的名称将与分组中具有该名称的玩家一样多次重复 -
哇,我之前使用代码将所有名称合并为一个,然后我创建了一个 json 文件并尝试再次执行此操作! @juanpa.arrivillaga
标签: python list dictionary nested for-in-loop