【问题标题】:My code is producing indexError我的代码正在产生 indexError
【发布时间】:2014-05-25 16:43:40
【问题描述】:

我的代码出现以下错误,谁能帮助我解决问题

如果 (RecentScores[count].Score)

def rankScores(RecentScores):
  noMoreSwaps = False
  while not noMoreSwaps:
    noMoreSwaps = True
    for count in range (1,len(RecentScores)):                                  
      if (RecentScores[count].Score) < (RecentScores[count + 1].Score):
        noMoreSwaps = False
        tempScore = RecentScores[count].Score
        tempName = RecentScores[count].Name
        RecentScores[count].Score = RecentScores[count+1].Score      
        RecentScores[count].Name = RecentScores[count+1].Name
        RecentScores[count+1].Score = tempScore
        RecentScores[count+1].Name = tempName
  DisplayRecentScores(RecentScores)

如果有人能帮忙,将不胜感激

【问题讨论】:

  • 我建议您阅读并关注PEP-0008

标签: python-3.x indexing syntax-error


【解决方案1】:

大多数编程语言中的索引以 0 开头。在行中

for count in range (1,len(RecentScores)): 

您正在从1 循环到length - 1(我正在调用lengthlen(RecentScores))。但是在行

if (RecentScores[count].Score) < (RecentScores[count + 1].Score):

您正在使用索引访问list/tuple

count + 1

假设循环在 last 迭代中。 count 的值将是 length - 1。然后,在if 条件下,您尝试使用

访问list/tuple
RecentScores[length - 1 + 1]

相当于

RecentScores[length]

这将引发异常,因为您正在访问高于允许的索引。

如何解决?

为了避免使用不允许的索引,您可以将循环范围更改为较小的:

for count in range (1, len(RecentScores) - 1): 

【讨论】:

    【解决方案2】:

    for count in range(0,len(RecentScores)-1): 永远记住索引从 0 开始到长度为 1。而且由于您在 index+1 处访问某些内容,因此您还必须减去 1,因为 range(a,b) 从 a 变为 b-1

    【讨论】:

      【解决方案3】:
      for count in range (1,len(RecentScores)):                                  
        if (RecentScores[count].Score) < (RecentScores[count + 1].Score):
      

      count 在这个循环中的最大值是RecentScores 的长度。 然后在循环的最后一次迭代中,您尝试通过以下方式访问结束后的循环: RecentScores[count + 1]

      尝试访问它会得到你看到的IndexError: list index out of range

      循环索引从 0 开始,因此要解决此问题,您需要更改循环操作的范围:

          for count in range (0,len(RecentScores)-1): 
      

      如果您想要按照评论的建议对整个分数列表进行排序(请注意,这不是问题中的代码所做的,而是),那么最好这样做:

      sortedScores = sorted(RecentScores, key=lambda x: x.Score, reverse=True)
      

      【讨论】:

      • 谢谢!那么我该如何解决呢?假设我希望程序按顺序对所有分数进行排序
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-15
      • 1970-01-01
      • 2010-12-08
      • 1970-01-01
      • 2020-09-22
      • 1970-01-01
      • 2015-05-15
      相关资源
      最近更新 更多