【问题标题】:List Index Out of Range? for Scores列表索引超出范围?分数
【发布时间】:2019-06-04 13:50:05
【问题描述】:

我正在尝试使用 Python 和 BeautifulSoup 遍历我从 Patriots.com 得分中获得的团队列表。我使用抓取和循环来获取 2001 年至 2018 年间每年的分数、团队和周数。2001 年之后,我得到一个列表索引超出范围错误

我尝试更改多项内容,例如我使用的整数或列表的 len() 是否需要 int()

m = 0
    while m < int(len(the_teams)):
      m = m+1
      q = the_scores[m].split('-')
      val = []
      for y in q:
        int_val = int(y)
        val.append(int_val)
      if val[0] > val[1]:
        print("The Patriots won against the " + the_teams[m] + " during " 
+ the_game[m] + " with a score of " + the_scores[m] + "!")
      else:
        print("The Patriots lost against the " + the_teams[m] + " during 
" +the_game[m] + " with a score of " + the_scores[m] + ".")

我希望在最后的打印语句中以 2 种格式输出每场比赛及其得分

【问题讨论】:

  • 请提供您的输入数据,以便我们帮助调试。自行在代码中添加大量 print() 以查看发生了什么。

标签: python while-loop indexoutofrangeexception


【解决方案1】:

在检查它是否为有效索引之后,进行分析之前,您正在递增索引。

如果你将m = m+ 1 - 或者更pythonic的m += 1 - 移动到while循环的底部,而不是顶部,它应该会按预期工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-31
    • 2020-09-17
    • 1970-01-01
    • 1970-01-01
    • 2018-12-16
    • 2011-06-14
    • 2016-06-04
    • 1970-01-01
    相关资源
    最近更新 更多