嵌套循环导致python

时间:2015-10-08 14:30:20

标签: python json api for-loop dictionary

我的小程序使用Riot API(游戏),我将玩家放入'盟友队'或'敌方队'。由于数据来自JSON,因此涉及很多列表和词典,我的问题可能源于那里,但我无法找到原因。

以下是导致此问题的部分:

first_game_test = game_list[0]
summ_team_ID = first_game_test["teamId"]
summoners_in_game = first_game_test["fellowPlayers"]
ally_team = []
enemy_team = []
for i in range(len(summoners_in_game)):
    for name, value in summoners_in_game[i].iteritems():
        if summoners_in_game[i]["teamId"] == summ_team_ID:
            #if summoners_in_game[i] not in ally_team:
                summoner_name = idtosummoner.idToSummonerName(summoners_in_game[i]['summonerId'])
                summoner_champ = champion_id.champIdGet(summoners_in_game[i]['championId'])
                ally_team.append({summoner_name: summoner_champ})
        else:
            #if summoners_in_game[i] not in enemy_team:
                enemy_team.append(summoners_in_game[i])

已多次检查idtosummonerchampion_id个模块;我很确定这个问题不是源于此。 如您所见,我使用了一个简单的重复检查修复程序(已注释掉)。然而,它开始混乱进一步编码:summoner_namesummoner_champ变量导致第3或第4个索引出错(我还没有将行添加到else,因为我想先解决这个问题。

控制台输出显示以下内容:

PS C:\Users\ptnfolder> python matchhistory.py
Nussen
Nussen
Nussen
kimbb
Traceback (most recent call last):
  File "matchhistory.py", line 67, in <module>
    matchHistory("thebirdistheword")
  File "matchhistory.py", line 39, in matchHistory
    print idtosummoner.idToSummonerName(summoners_in_game[i].get('summonerId'))
  File "C:\Users\ptnfolder\idtosummoner.py", line 10, in idToSummonerName
    champ_name_dict = json_data[str(summID)]
KeyError: '29716673'

奇怪的是,KeyError实际应该解析为'kimbb' - 因为for循环以某种方式将每个条目变为三倍 - ;它工作一次,然后程序崩溃。

1 个答案:

答案 0 :(得分:0)

您正在循环遍历列表中词典的键和值

for i in range(len(summoners_in_game)):
    for name, value in summoners_in_game[i].iteritems():

因此,对于每个键值对,执行循环体。在循环体中,您将测试特定的键:

if summoners_in_game[i]["teamId"] == summ_team_ID:

因此,对于字典中的每个键,您可以测试'teamId'键的值是否与summ_team_ID匹配。

执行的次数与字典中的键一样多,但您只想测试一个键。

只需删除键值对上的循环:

for i in range(len(summoners_in_game)):
    if summoners_in_game[i]["teamId"] == summ_team_ID:
        summoner_name = idtosummoner.idToSummonerName(summoners_in_game[i]['summonerId'])
        summoner_champ = champion_id.champIdGet(summoners_in_game[i]['championId'])
        ally_team.append({summoner_name: summoner_champ})
    else:
        enemy_team.append(summoners_in_game[i])

不是使用range()生成的索引,而是直接遍历列表 ,而不必继续编制索引:

for team in summoners_in_game:
    if team["teamId"] == summ_team_ID:
        summoner_name = idtosummoner.idToSummonerName(team['summonerId'])
        summoner_champ = champion_id.champIdGet(team['championId'])
        ally_team.append({summoner_name: summoner_champ})
    else:
        enemy_team.append(team)