Python 列表 index() 方法


描述

Python 列表 index() 方法用於從列表中找出某個對象第一個匹配項的索引位置,如果這個對象不在列表中會報一個異常。 

語法

index() 方法語法:

L.index(obj[,start=0[,stop=len(L)]])

參數

  • obj -- 查找的對象。
  • start -- 可選參數,開始索引,默認為0。(可單獨指定)
  • stop -- 可選參數,結束索引,默認為列表的長度。(不能單獨指定)

返回值

如果包含檢索的對象返回開始的索引值,否則拋出異常。

實例

以下實例展示了 index() 方法的使用方法:

# !/usr/bin/python3

L = ['Google', 'Runoob', 'Taobao']
print(L.index('Taobao'))
print(L.index('Google',1))

以上實例輸出結果如下:

2
Traceback (most recent call last):
  File "test.py", Lne 22, in <module>
    print(tu.index('Google',1))
ValueError: tuple.index(x): x not in tuple


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM