Python-IndexError: list index out of range
生活随笔
收集整理的這篇文章主要介紹了
Python-IndexError: list index out of range
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Error:IndexError: list index out of range
Where?
對Python中有序序列進行按索引取值的時候,出現這個異常
?
Why?
對于有序序列: 字符串 str 、列表 list 、元組 tuple進行按索引取值的時候,默認范圍為 0 ~ len(有序序列)-1,計數從0開始,而不是從1開始,最后一位索引則為總長度減去1。當然也可以使用?負數表示從倒數第幾個,計數從-1開始,則對于有序序列,總體范圍為 -len(有序序列) ~ len(有序序列)-1,如果輸入的取值結果不在這個范圍內,則報這個錯
?
Way?
檢查索引是否在?-len(有序序列) ~ len(有序序列)-1?范圍內,修改正確
?
錯誤代碼:
name = "beimenchuixue" students = ["beimenchuixue", "boKeYuan", "Python", "Golang"] print(name[20]) print(students[4])
正確代碼:
name = "beimenchuixue" students = ["beimenchuixue", "boKeYuan", "Python", "Golang"] print(name[3]) print(students[3])?
?
轉載于:https://www.cnblogs.com/2bjiujiu/p/9063864.html
總結
以上是生活随笔為你收集整理的Python-IndexError: list index out of range的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: (转)zabbix3.4使用percon
- 下一篇: 2017-2018-2 20179216