鱼C论坛

 找回密码
 立即注册
查看: 1344|回复: 5

请问一下为什么会出现out of range的问题

[复制链接]
发表于 2019-8-13 11:49:28 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
代码如下:
    def _calc(self):
        self.lasted = []
        self.prompt = '总共运行了'
        for index in range(6):
            self_lasted = self.end[index] - self.begin[index]
            print(index)
            if index == 1:
                if self_lasted < 0:
                    self_lasted += 60
                    self.lasted.append(self_lasted)
                else:
                    self.lasted.append(self_lasted)
            print(self_lasted)
            if self.lasted[index]:
                self.prompt += (str(self.lasted[index]) + self.unit[index])

这是小甲鱼的计时器那一章课后题的一部分,我将它做成可以进行时间单位转换,例如如果秒为负数的话就将它改为正数。然而运行之后出现报错:if self.lasted[index]:这一行,出现
IndexError: list index out of range
不知道是什么问题,我感觉思路没错啊?谢谢大佬!!
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2019-8-13 11:56:20 | 显示全部楼层
这样试试
  1. def _calc(self):
  2.         self.lasted = []
  3.         self.prompt = '总共运行了'
  4.         for index in range(6):
  5.             self_lasted = self.end[index] - self.begin[index]
  6.             print(index)
  7.             if self_lasted < 0:
  8.                 self_lasted += 60
  9.                 self.lasted.append(self_lasted)
  10.             else:
  11.                 self.lasted.append(self_lasted)
  12.             print(self_lasted)
  13.             if self.lasted[index]:
  14.                 self.prompt += (str(self.lasted[index]) + self.unit[index])
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-8-13 12:06:15 | 显示全部楼层
本帖最后由 jackz007 于 2019-8-13 13:27 编辑

      列表 self . lasted 下标超界,也就是说,索引值 index 超出了列表的可索引范围。

  1.     def _calc(self):
  2.         self.lasted = []
  3. . . . . . .
  4.         for index in range(6):
  5. . . . . . .
  6.             if index == 1:
  7. . . . . . .
  8.                     self.lasted.append(self_lasted)
  9. . . . . . .
  10.             if self.lasted[index]:
复制代码


      在函数入口,列表 self . lasted 被初始化为一个空表,在后面的循环中,只有当 index == 1 的时候,才会有机会添加 1 个元素,也就是说,self . lasted 最终只会有 1 个元素,而并非楼主预期的 6 个,所以,当使用大于 0 的 index 索引 self . lasted 时,自然就会出错了。

   
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2019-8-13 15:15:04 | 显示全部楼层
jackz007 发表于 2019-8-13 12:06
列表 self . lasted 下标超界,也就是说,索引值 index 超出了列表的可索引范围。

其实我原来是有列举了index==1,index==2一直到index==6的几种情况的,可是还是不行,因为从index == 1就运行不了了。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-8-13 16:07:58 | 显示全部楼层
winter宇 发表于 2019-8-13 15:15
其实我原来是有列举了index==1,index==2一直到index==6的几种情况的,可是还是不行,因为从index == 1就 ...

一般是 列表里面没有数据  所以即便你用索引0 去取数据 也取不到
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2026-1-17 15:47

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表