【问题标题】:Why does updating a dictionary remove the rest of the dictionaries from my nested array?为什么更新字典会从我的嵌套数组中删除其余的字典?
【发布时间】: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


【解决方案1】:

只是为了它的价值,我会回去认真思考每一行的真正作用。通过调用变量objx,你也会让事情变得更难。计算平均值可以这样完成:

for player in data: # data is poorly named, try players or players_data
    player['Average'] = sum(float(tourny['Points']) for tourny in player['Tournament']) / len(player['Tournament'])
    for tourny in player['Tournament']:
        tourny['Difference'] = float(tourny['Points']) - float(player['Average'])

留给你:

{'Player_Name': 'Rory McIlroy', 
 'Tournament': [{
     'Name': 'Arnold Palmer Invitational presented by Mastercard', 
     'Points': '68.10', 
     'Salary': '12200.00', 
     'Difference': -33.46666666666667},
    {
     'Name': 'World Golf Championships-Mexico Championship', 
     'Points': '103.30', 
     'Salary': '12200.00', 
     'Difference': 1.7333333333333343}, # .....etc 
  'Average': 101.566666666666666
}

当您在代码中使用名称来描述它们所代表的内容时,大量的优化会立即变得显而易见。试一试!

【讨论】:

    猜你喜欢
    • 2022-06-13
    • 2018-04-14
    • 1970-01-01
    • 2022-12-22
    • 1970-01-01
    • 2019-12-04
    • 2017-03-08
    • 1970-01-01
    相关资源
    最近更新 更多