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 原创文章,作者:GDVG7,如若转载,请注明出处:https://www.506064.com/n/128657.html
微信扫一扫 
支付宝扫一扫