python 中的index()
函數有助于返回元組中給定元素的索引。我們還可以通過元組提供搜索的起點和終點。
**tuple.index(element, start, end)** #where the element may be string, number, list, etc
索引()參數:
index()
方法采用三個參數。此方法的輸出應該是指示元素位置的整數值。
參數 | 描述 | 必需/可選 |
---|---|---|
元素 | 要搜索的元素 | 需要 |
開始 | 從此索引開始搜索 | 可選擇的 |
目標 | 搜索元素直到這個索引 | 可選擇的 |
索引()返回值
如果該方法找到給定元素的多個匹配項,它將只返回第一個匹配項的索引。
| 投入 | 返回值 | | 元素 | 元素索引 | | 如果沒有元素 | ValueError exception(值錯誤異常) |
Python 中index()
方法的示例
例 1:如何找到元組中元素的索引?
# alphabet tuple
alphabet = ('a', 'b', 'c', 'e', 'd', 'e', 'f')
# index of 'c' in alphabet
indexpos = alphabet.index('c')
print('The index of c:', indexpos)
# element 'e' is searched
# index of the first 'e' is returned
indexpos = alphabet.index('e')
print('The index of e:', indexpos)
輸出:
The index of c: 2
The index of e: 3
例 2:如何找到缺失元素的索引?
# alphabet tuple
alphabet = ('a', 'b', 'c', 'd', 'e', 'f')
# index of 'g' in alphabet
indexpos = alphabet.index('g')
print('The index of g:', indexpos)
輸出:
ValueError: alphabet.index('g'): g not in tuple