如何使用前一个键解析json文件?

2024-05-19 19:18:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我早就有过这样的JSON(我需要找出每个团队摧毁的兵营数量):

[{'player_slot': 129,
  'slot': 6,
  'team': 3,
  'time': 2117.449,
  'type': 'CHAT_MESSAGE_TOWER_KILL'},
 {'player_slot': 132,
  'slot': 9,
  'team': 3,
  'time': 2156.047,
  'type': 'CHAT_MESSAGE_TOWER_KILL'},
 {'key': '512', 'time': 2178.992, 'type': 'CHAT_MESSAGE_BARRACKS_KILL'},
 {'player_slot': 4,
  'slot': 4,
  'team': 2,
  'time': 2326.829,
  'type': 'CHAT_MESSAGE_TOWER_KILL'},
{'key': '2', 'time': 2333.384, 'type': 'CHAT_MESSAGE_BARRACKS_KILL'}],
 {'key': '2', 'time': 2340.384, 'type': 'CHAT_MESSAGE_BARRACKS_KILL'}]

radiant_barracks_kills = 0
dire_barracks_kills = 0
for objective in match['objectives']:
    for i,e in enumerate(objective):
        if e['type'] == 'CHAT_MESSAGE_BARRACKS_KILL':
            if objective[i-1]['slot'] < 5:
                radiant_barracks_kills += 1
            if objective[i-1]['slot'] >= 5:
                dire_barracks_kills += 1

TypeError: string indices must be integers

有必要在循环中运行所有这些字典列表,并确定每个小组被摧毁的兵营数量。你知道吗


Tags: keymessageiftimetypechatteamkill
1条回答
网友
1楼 · 发布于 2024-05-19 19:18:00

假设,如您所说,“match['objectives']包含字典列表”,那么您的问题是您进行了额外的迭代。如果您尝试print的类型和值e

for objective in match['objectives']:
    for i,e in enumerate(objective):
        print(type(e), e)

你会得到:

<class 'str'> player_slot
<class 'str'> slot
<class 'str'> team
<class 'str'> time
<class 'str'> type
<class 'str'> player_slot
<class 'str'> slot
<class 'str'> team
<class 'str'> time
<class 'str'> type
...

第一个for循环已经在字典列表上迭代。所以objective已经是一本字典了。当您对enumerate执行第二个for循环时,它将在字典的上迭代,然后e['type']将失败,因为这就像您执行了:

"player_slot"['type']

这将导致“TypeError:字符串索引必须是整数”。你知道吗

你只需要迭代一次。你知道吗

radiant_barracks_kills = 0
dire_barracks_kills = 0
list_of_objectives = match['objectives']  # [{..},{..},..{..}]

for i, objective in enumerate(list_of_objectives):
    # objective is a dict
    if objective['type'] == 'CHAT_MESSAGE_BARRACKS_KILL':
        if list_of_objectives[i-1]['slot'] < 5:
            radiant_barracks_kills += 1
        if list_of_objectives[i-1]['slot'] >= 5:
            dire_barracks_kills += 1

相关问题 更多 >