【问题标题】:nested loops causing unwanted duplicate list entries in python嵌套循环导致python中不需要的重复列表条目
【发布时间】:2016-01-06 05:57:39
【问题描述】:

我的小程序使用 Riot API(游戏),我将玩家放入“盟友团队”或“敌人团队”。由于数据来自 JSON,因此涉及到很多列表和 dicts,我的问题可能源于那里,尽管我一直无法找到。

这是导致问题的部分:

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 循环以某种方式将每个条目增加三倍 -;它运行一次,然后程序崩溃。

【问题讨论】:

    标签: python json api for-loop dictionary


    【解决方案1】:

    您正在遍历列表中字典的键和值

    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)
    

    【讨论】:

    • 我明白了!我认为有必要在循环内循环才能访问嵌套字典。现在完美运行,非常感谢!
    猜你喜欢
    • 2021-07-20
    • 1970-01-01
    • 2016-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多