鱼C论坛

 找回密码
 立即注册
查看: 3060|回复: 4

tuple index out of range

[复制链接]
发表于 2019-10-3 23:10:10 | 显示全部楼层 |阅读模式

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

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

x
  1. number4 = (1, 3, 2, 4, 5, 6, 7, 8)      
  2. for y in number4:   
  3.     if (y+2) % 2 == 0:
  4.    print(number4[y], number4[y+1])
复制代码


File "/Users/fanglei/PycharmProjects/A/1.py", line 6, in <module>
    print(number4[y], number4[y+1])
IndexError: tuple index out of range
2 4
5 6
7 8

Process finished with exit code 1
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2019-10-3 23:16:21 | 显示全部楼层
y是元组的元素,你又拿来做索引值,本身就不妥。
当读到7时,number4[7]已是最后一个元素,number4[7 + 1]就越界了。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-10-3 23:16:23 | 显示全部楼层
本帖最后由 凌九霄 于 2019-10-3 23:57 编辑

没明白代码的意图
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-10-4 00:10:36 | 显示全部楼层
  1. number4 = (1, 3, 2, 4, 5, 6, 7, 8)
  2. index = 0
  3. for y in number4:   
  4.     if index % 2 == 0:
  5.        print(number4[index], number4[index+1])

  6.     index += 1
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-10-4 07:53:03 | 显示全部楼层
因为 number4 里有个 7,number4[7] 是 8,但 number4[7 + 1] 就越界了。建议这样改:
  1. number4 = (1, 3, 2, 4, 5, 6, 7, 8)      
  2. for y in number4:   
  3.     if (y + 2) % 2 == 0:
  4.        print(number4[y - 2], number4[y - 1])
复制代码

运行结果:
  1. 1 3
  2. 2 4
  3. 5 6
  4. 7 8
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2026-1-19 18:38

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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