Index error saying that the index is out of range

时间:2019-04-17 02:51:37

标签: python python-3.x

I'm trying to return the sum of the numbers in the array, returning 0 for an empty array. Except the number 13 it doesn't count and the number immediately after 13.

def sum13(nums):
  p = 0
  for i in range(len(nums)):
    if nums[i] == 13 and nums[i + 1]:
      continue
    p += nums[i]
  return p

When I run it, it gives me an index error list index our of range, what am I doing wrong?

4 个答案:

答案 0 :(得分:2)

这是您想要的:

def sum13(nums):
    p = 0
    skip_next = False
    for i in range(len(nums)):
        if nums[i] == 13:
           skip_next = True
           continue
        if skip_next:
            skip_next = False
            continue
        p += nums[i]
    return p

答案 1 :(得分:1)

range(len(nums))的大小与nums的大小相同。
因此,不存在nums[i+1]

答案 2 :(得分:0)

if nums[i]==13 and nums[i+1]不起作用,因为i + 1会大于列表的长度,因此nums[i]+1只会检查数字是否存在,不会跳过。
您想跳过一个数字,如果它是13或之前的数字是13,则如下所示

def sum13(nums):

    p = 0
    for i in range(len(nums)):
        if nums[i] == 13 or nums[i-1] == 13:
            continue
        else:
            p += nums[i]
    return p

print(sum13([1,2,13,14,5,6,7]))
#21
print(sum13([13,14]))
#0
print(sum13([13]))
#0
print(sum13([]))
#0

答案 3 :(得分:0)

问题出在nums[i+1]上,它不在您的列表范围内。这是使用while的另一种解决方案。

def sum13(nums):
    p=0; i=0
    while i < len(nums):
        if nums[i]==13:
            i = i + 2 #exclude the position after 13
            continue
        else:
            p+=nums[i]
            i=i+1
    return p