嵌套循环导致python中不需要的重复列表项

2024-06-16 12:57:14 发布

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

我的小程序使用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])

idtosummonerchampion_id模块已经被检查了多次;我非常确定问题并非源于此。 如您所见,我使用了一个简单的重复检查修复(注释掉)。但是,它开始扰乱进一步的编码:变量summoner_name,和summoner_champ在第3或第4个索引处导致错误(我还没有向else添加行,因为我想先解决这个问题)。在

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

^{pr2}$

奇怪的是KeyError实际上应该解析为'kimbb',因为for循环会以某种方式使每个条目增加三倍;它只工作一次,然后程序就会崩溃。在


Tags: nameintest程序gameforifteam
1条回答
网友
1楼 · 发布于 2024-06-16 12:57:14

您正在列表中的字典的键和值上循环:

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

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

^{pr2}$

因此,对于字典中的每个键,测试'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)

相关问题 更多 >