迭代数组导致IndexError:列表索引超出范围错误

时间:2018-03-11 19:18:44

标签: python arrays data-structures

我一直收到" IndexError:列表索引超出范围"错误,但我不确定为什么会出现这种情况

def missingNumber(nums):
   sorted_nums = sorted(nums)
   for num in sorted_nums[1:]:
      print(num,sorted_nums[num]-1)
      if ((sorted_nums[num] - sorted_nums[num]-1) > 1):
         res = (num + num + 1)/2
   return res
print(missingNumber([3,0,1]))

1 个答案:

答案 0 :(得分:0)

示例:nums = [3,0,1]

//sorted_nums = [0,1,3]
//sorted_nums[1:] = [1,3]
for num in sorted_nums[1:]:
  //here num is element not index
  //so sorted_nums[3] is "IndexError: list index out of range"
  print(num,sorted_nums[num]-1)   
  if ((sorted_nums[num] - sorted_nums[num]-1) > 1):
     res = (num + num + 1)/2
return res

这样做

sorted_nums = [0,1,3]
for num in range(1,len(sorted_nums)):
  print(num,sorted_nums[num]-1)    

  if ((sorted_nums[num] - sorted_nums[num-1]) > 1):  // 1-0 is not greater than 1
     res = (sorted_nums[num] + sorted_nums[num-1])/2
     return res

第一次迭代

 num = 1, sorted_nums[num] = 1,sorted_nums[num-1] =0 
 1-0 is not greater than 1

第二次迭代

 num = 2, sorted_nums[num] = 3,sorted_nums[num-1] =1 
 3-1 = 2 is greater than 1 
 so res = (3 + 1)/2 = 4/2 = 2
 missing number is 2