创新互联Python教程:Pythonindex()
python 中的index()函数有助于返回元组中给定元素的索引。我们还可以通过元组提供搜索的起点和终点。

10年积累的网站设计制作、成都网站设计经验,可以快速应对客户对网站的新想法和需求。提供各种问题对应的解决方案。让选择我们的客户得到更好、更有力的网络服务。我虽然不认识你,你也不认识我。但先网站制作后付款的网站建设流程,更有花垣免费网站建设让你可以放心的选择与我们合作。
**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 网站栏目:创新互联Python教程:Pythonindex()
本文链接:http://www.jxjierui.cn/article/cdoopsp.html


咨询
建站咨询
