Python 我的for循环出现问题,并收到以下消息:keyrerror:2
我得到了以下错误:Stats PlayerList=competitionList[j]keyrerror:2 我在competitionList中保存了许多列表,这是一本字典。我想遍历字典中列表中的所有对象Python 我的for循环出现问题,并收到以下消息:keyrerror:2,python,for-loop,iteration,Python,For Loop,Iteration,我得到了以下错误:Stats PlayerList=competitionList[j]keyrerror:2 我在competitionList中保存了许多列表,这是一本字典。我想遍历字典中列表中的所有对象 def Stats(competitionList, playerList): no_of_competitions = int(len(competitionList)) x = (len(playerList)) for i in ran
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)
错误只是在这一行中说明:
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)
PlayerList=competitionList[j]
dictionary competitionList不包含rangex中的一个键,在本例中为键2。确保:
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)
此范围内的所有值均显示在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)
for players in competitionList.values():
for player in players:
print("player: ", player.name)
print ("list : ", player.name, player.victories)
您可以使用j访问competitionList。但是j指的是x,x是playerList的长度。玩家列表和竞赛列表可以延迟长度,这就是为什么会出现这种错误。为什么要投int no_of_竞赛?它已经是一个整数了。换言之,说明错误:您的字典中没有整数2的键。谢谢,代码正在运行。一个小问题是,当你添加值时,它是如何工作的?看看,值检索字典的值,这是我们感兴趣的值。我们尤其可以忽略这个问题的关键。
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)