为了账号安全,请及时绑定邮箱和手机立即绑定

为什么此代码会返回“弹出索引超出范围”?

为什么此代码会返回“弹出索引超出范围”?

冉冉说 2022-12-20 11:21:27
我试图理解导致这种情况的逻辑和过程,但仍然不明白为什么会这样。抱歉,如果这是一个非常简单/糟糕的问题。这是问题:返回数组中数字的总和,除了忽略以 6 开头并延伸到下一个 7 的数字部分(每个 6 后面至少有一个 7)。没有数字则返回 0。这是有错误的代码:def sum67(nums):  ans = 0  if len(nums) == 0:    return 0   elif 6 not in nums:    for val in nums:      ans += val    return ans    elif 6 in nums:    x = nums.index(6)    y = nums.index(7, x)    for i in range(x, y):      nums.pop(i)  for val in nums:    ans += val  return ans这是错误:pop index out of range
查看完整描述

1 回答

?
MMTTMM

TA贡献1869条经验 获得超4个赞

哇哦!我刚刚了解了该del功能。


我的解决方案是更换:


elif 6 in nums:

  x = nums.index(6)

  y = nums.index(7, x)

  for i in range(x, y):

    nums.pop(i)` 

和:


while 6 in nums:

  x = nums.index(6)

  y = nums.index(7, x)

  del nums[x:y+1]


查看完整回答
反对 回复 2022-12-20
  • 1 回答
  • 0 关注
  • 100 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号