我的小程序使用Riot API(游戏),我把玩家分为“盟友队”或“敌人队”。由于数据来自JSON,因此涉及到大量的列表和dict,我的问题可能源于此,尽管我还无法找到其中的位置。在
以下是导致问题的部分:
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])
idtosummoner
和champion_id
模块已经被检查了多次;我非常确定问题并非源于此。
如您所见,我使用了一个简单的重复检查修复(注释掉)。但是,它开始扰乱进一步的编码:变量summoner_name
,和summoner_champ
在第3或第4个索引处导致错误(我还没有向else
添加行,因为我想先解决这个问题)。在
控制台输出显示以下内容:
^{pr2}$奇怪的是KeyError
实际上应该解析为'kimbb'
,因为for循环会以某种方式使每个条目增加三倍;它只工作一次,然后程序就会崩溃。在
您正在列表中的字典的键和值上循环:
因此,对于每个键值对,执行循环体。在循环体中,测试一个特定的键:
^{pr2}$因此,对于字典中的每个键,测试
'teamId'
键的值是否与summ_team_ID
匹配。在它执行的次数与字典中的键相同,但您只想测试其中一个键。在
只需移除键值对上的循环:
与使用
range()
生成的索引不同,您只需直接循环列表即可,而不必继续索引:相关问题 更多 >
编程相关推荐