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

我试图理解导致这种情况的逻辑和过程,但仍然不明白为什么会这样。抱歉,如果这是一个非常简单/糟糕的问题。


这是问题:


返回数组中数字的总和,除了忽略以 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


冉冉说
浏览 101回答 1
1回答

MMTTMM

哇哦!我刚刚了解了该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]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python