我的forloop有问题,收到以下消息:KeyError:2

2024-05-16 07:16:27 发布

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

我得到以下错误:Stats PlayerList=competitionList[j]KeyError:2 我在competitionList中保存了许多列表,这是一本字典。我想遍历字典中列表中的所有对象。你知道吗

def Stats(competitionList, playerList):
        no_of_competitions = int(len(competitionList))
        x = (len(playerList))
        for i in range(no_of_competitions):
            for j in range (int(x)):
            #My error occurs here
                PlayerList=competitionList[j]
                for player in PlayerList: 
                    print("player: ", player.name)
                    print ("list :", player.name, player.victories)

Tags: ofnoin列表forlen字典stats
2条回答

使用j访问competitionList。但是jxxplayerList的长度。playerListcompetitionList在长度上可以延迟,所以这就是为什么会出现这种类型的错误。你知道吗

错误只是在这行中指出:

PlayerList=competitionList[j]

字典competitionList不包含range(x)中的一个键,在本例中是键2。确保:

  1. 范围中的所有值都存在于competitionList
  2. 或者只迭代字典中实际存在的值

对于第二种选择,这应该简化事情并使其工作:

for players in competitionList.values():
    for player in players:
        print("player: ", player.name)
        print ("list : ", player.name, player.victories)

相关问题 更多 >