[英]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
錯誤是由最后一個if
產生的,我不明白為什么
這意味着len(nums) == 0
。 嘗試類似的東西
if nums and nums[0] != 13:
如果您使用 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
當nums
為空時, for
循環根本不會執行。
因為 Python 在if
語句的計算中使用了“提前終止”,這意味着一旦檢測到ix == 0
為 True,當ix
為 0 時,它不會計算nums[ix-1]
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.