Python中调用存在的列表索引时出现“list index out of range”错误。

huangapple go评论74阅读模式
英文:

Python — "list index out of range" error when calling a list index that does exists

问题

当将[1, 2, 3]输入作为此“function”的参数时,我会收到“list index out of range”错误。我希望能够调用nums[1]来获取“list”的第二个索引,例如在这个示例中是2。但是我无法这样做,有人可以帮助我找出原因吗?

谢谢

def sum2(nums):
  if nums == []:
    return 0
  elif nums <= 1:
    return nums[0]
  elif nums >= 3:
    return nums[0] + nums[1]
英文:

When inputting [1, 2, 3] as the parameter for this function, I get the list index out of range error. I would expect to be able to call nums[1] to get the second index of the list — 2 in this example. But I cannot, can anyone help me figure out why?

Thank you

def sum2(nums):
  if nums == []:
    return 0
  elif nums &lt;= 1:
    return nums[0]
  elif nums &gt;= 3:
    return nums[0] + nums[1]

答案1

得分: 3

问题出在你的if-elif语句的条件上。你正在将一个list(nums)与一个整数(1或3)进行比较,这是无效的。你应该检查list的长度而不是它的内容。这是已经更正的代码:

def sum2(nums):
  if len(nums) == 0:
    return 0
  elif len(nums) <= 1:
    return nums[0]
  elif len(nums) >= 3:
    return nums[0] + nums[1]

# 输入 [1, 2, 3]
# len([1, 2, 3]) >= 3 ==> True and nums[0] = 1 + nums[1] = 2 ==> 返回 3
# 输出 3

希望答案对你足够清晰,如果你有任何问题,我会在这里帮助你。

英文:

The issue is with the conditions in your if-elif statements. You are comparing a list (nums) with an integer (1 or 3), which is not valid. You should be checking the length of the list instead. Here's the corrected code:

def sum2(nums):
  if len(nums) == 0:
    return 0
  elif len(nums) &lt;= 1:
    return nums[0]
  elif len(nums) &gt;= 3:
    return nums[0] + nums[1]

# input [1, 2, 3]
#len([1, 2, 3]) &gt;= 3 ==&gt; True and nums[0] = 1 + nums[1] = 2 ==&gt; return 3
# output 3

I hope the answer is clear enough for you and if you have any questions I am here to help you

huangapple
  • 本文由 发表于 2023年7月12日 20:37:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76670625.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定