英文:
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 <= 1:
return nums[0]
elif nums >= 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) <= 1:
return nums[0]
elif len(nums) >= 3:
return nums[0] + nums[1]
# input [1, 2, 3]
#len([1, 2, 3]) >= 3 ==> True and nums[0] = 1 + nums[1] = 2 ==> 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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论