Python 的 list.index(~) 方法返回列表中指定元素第一次出現的位置。
參數
1. x | any
要在列表中搜索的元素。
2. start | number | optional
開始搜索的索引位置(含)。默認為 0。
3. end | number | optional
結束搜索的索引位置(不包括)。默認為列表長度(即列表中最後一個索引位置 + 1)。
返回值
列表中元素x 第一次出現的索引位置。
例子
基本用法
返回 animals 列表中第一次出現 'koala' 的索引位置:
animals = ['koala', 'rabbit', 'dog', 'cat', 'koala']
animals.index('koala')
0
請注意,Python 中的索引位置從 0 開始,而不是 1。因此,我們看到 0 的返回值,因為 'koala' 是列表 animals 中的第一個元素。
ValueError
返回 animals 列表中第一次出現 'panda' 的索引位置:
animals = ['koala', 'rabbit', 'dog', 'cat', 'koala']
animals.index('panda')
ValueError: 'panda' is not in list
由於 'panda' 不存在於列表 animals 中,因此引發 ValueError:
啟動參數
要在 animals 的索引位置 1 處開始搜索 'koala':
animals = ['koala', 'rabbit', 'dog', 'cat', 'koala']
animals.index('koala', 1)
4
4 返回為 'koala' 首先出現在 animals 中的索引位置 1 之後的索引位置 4(第 5 個元素)。
結束參數
要在 animals 中倒數第三個元素處結束對 'cat' 的搜索:
animals = ['koala', 'rabbit', 'dog', 'cat', 'koala']
animals.index('cat', 0, -2)
ValueError: 'cat' is not in list
搜索排除索引位置 end 處的元素(在本例中為 -2(倒數第二個元素),該元素被元素 'cat' 占用)。結果,搜索在檢查索引位置 -3 ( 'dog' ) 處的元素後結束,這就是拋出 ValueError 的原因。
相關用法
- Python List index()用法及代碼示例
 - Python List insert()用法及代碼示例
 - Python List insert方法用法及代碼示例
 - Python List remove()用法及代碼示例
 - Python List clear()用法及代碼示例
 - Python List reverse()用法及代碼示例
 - Python List copy方法用法及代碼示例
 - Python List sort方法用法及代碼示例
 - Python List extend方法用法及代碼示例
 - Python List append()用法及代碼示例
 - Python List cmp()用法及代碼示例
 - Python List remove方法用法及代碼示例
 - Python List append方法用法及代碼示例
 - Python List pop()用法及代碼示例
 - Python List sort()用法及代碼示例
 - Python List pop方法用法及代碼示例
 - Python List reverse方法用法及代碼示例
 - Python List list()用法及代碼示例
 - Python List max()用法及代碼示例
 - Python List count()用法及代碼示例
 - Python List len()用法及代碼示例
 - Python List count方法用法及代碼示例
 - Python List min()用法及代碼示例
 - Python List clear方法用法及代碼示例
 - Python List copy()用法及代碼示例
 
注:本文由純淨天空篩選整理自Isshin Inada大神的英文原創作品 Python List | index method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
