![](/img/trans.png)
[英]IndexError: list index out of range in python, know the meaning, but don't understand why this happens
[英]Don't understand a Python List Index
因此,我不完全理解.index()
並且一直在弄亂一段代碼來嘗試理解它,但是它仍然沒有點擊我。
弄亂此列表時:
myList = [5024,3,True,6.5,12,1,2,2,2]
print(myList)
print(myList.index(2))
打印出來: 6
這6是哪里來的?
再舉一個例子:
myList = [5024,3,True,6.5,12,1,2,2,2]
print(myList)
print(myList.index(4))
解決此問題的原因: 4 is not in list
但是在打印時:
myList = [5024,3,True,6.5,12,1,2,2,2]
print(myList)
print(myList.index(1))
印數: 2
這是我不明白的。 程序是否計算該列表中出現了1次? 如果是這樣,當嘗試在此列表中使用.index(2)
時,它將打印出6
而不是5
。
這里發生了什么?
True
被解釋為1。
作為myList.index(value)
返回的第一個索引value
那么你所得到的值:
>>> myList = [5024,3,True,6.5,12,1,2,2,2]
>>> myList.index(2)
6
>>> myList.index(1)
2
如果要查找特定索引處的值,請使用:
myList[index]
數據結構 -如果您需要更多信息,請閱讀本文。
list.index(x)
返回值為x的第一項列表中的索引。 如果沒有這樣的項目,那就是錯誤的。
您可以按索引訪問列表中的元素。 索引從0
開始。 假設您有一個列表,讓我們看一下元素的索引:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
list_of_nums
[0 1 2 3 4 5 6 7 8 9 ]
索引
所以,如果你使用list_of_nums.index(3)
它會返回一個值的元素中第一次出現的索引3
在列表中,這是2
。
在您的情況下, myList.index(2)
返回值為2
的元素首次出現的索引6
。
myList.index(4)
返回'4 is not in list'
因為'4 is not in list'
中沒有這樣的元素,值為4
。 myList.index(1)
返回值為True
的元素,因為它是第一次出現的值為1
, True == 1
和False == 0
的元素。
因此,如果知道值,則可以在列表中找到任何元素的索引。 您也可以使用索引來獲取值,例如: myList[1]
3
我希望現在更加清楚。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.