简体   繁体   English

为什么我收到错误:列表索引超出范围

[英]Why I get the error: list index out of range

def sum13(nums):
  summ = 0
  for i in range(1, len(nums)):
    if nums[i] != 13 and nums[i-1] != 13:
     summ += nums[i]
  if nums[0] != 13:
    summ += nums[0]
  return summ

The error is produced by the last if and I don't understand why错误是由最后一个if产生的,我不明白为什么

That means len(nums) == 0 .这意味着len(nums) == 0 Try something like尝试类似的东西

if nums and nums[0] != 13:

If you use Python enumerate , rather than a loop counter, to track your position in the array you can simplify the code to have a single if statement, and eliminate the error if the length of the list is zero:如果您使用 Python enumerate而不是循环计数器来跟踪您在数组中的位置,您可以将代码简化为具有单个if语句,并在列表长度为零时消除错误:

def sum13(nums):
    summ = 0
    for ix, num in enumerate(nums):
        if ix == 0 or (num != 13 and nums[ix-1] != 13):
            summ += num
    return summ

When nums is empty, the for loop won't execute at all.nums为空时, for循环根本不会执行。

Because Python uses 'early termination' in the evaluation of if statements, it means that as soon as it detects that ix == 0 is True, it won't evaluate nums[ix-1] when ix is 0.因为 Python 在if语句的计算中使用了“提前终止”,这意味着一旦检测到ix == 0为 True,当ix为 0 时,它不会计算nums[ix-1]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM