列出 index() 方法
index() 方法用於獲取指定元素的索引,該方法使用此列表調用,元素可以作為參數提供,它返回列表中元素第一次出現的索引。
用法:
list_name.index(element)
參數:
element– 它表示要找到其索引的元素。
返回值:
這個方法的返回類型是<class 'int'>,它返回一個整數元素,該元素將是該元素第一次出現的索引,或者如果元素在列表中不存在,則返回一個 ValueError 。
範例1:
# Python List index() Method with Example
# declaring the list
cars = ["Porsche", "Audi", "Lexus", "Porsche", "Audi"]
# printing the list
print("cars:", cars)
# finding index of "Porsche"
pos = cars.index("Porsche")
print("Porsche's index is:", pos)
# finding index of "Lexus"
pos = cars.index("Lexus")
print("Lexus's index is:", pos)
輸出
cars: ['Porsche', 'Audi', 'Lexus', 'Porsche', 'Audi'] Porsche's index is:0 Lexus's index is:2
範例2:
# Python List index() Method with Example
# declaring the lists
x = ["ABC", "XYZ", "PQR","ABC", "XYZ", "PQR"]
y = ["PQR", "MNO", "YXZ", "YXZ"]
z = ["123", "456", "789"]
# printing the findex of given element
print('x.index("ABC"):', x.index("ABC"))
print('y.index("YXZ"):', y.index("YXZ"))
print('z.index("789"):', z.index("789"))
# ValueError
print('x.index("MNO"):', x.index("MNO"))
輸出
x.index("ABC"):0
y.index("YXZ"):2
z.index("789"):2
Traceback (most recent call last):
  File "main.py", line 14, in <module>
    print('x.index("MNO"):', x.index("MNO"))
ValueError:'MNO' is not in list
相關用法
- Python List remove()用法及代碼示例
 - Python List clear()用法及代碼示例
 - Python List pop()用法及代碼示例
 - Python List sort()用法及代碼示例
 - Python List count()用法及代碼示例
 - Python List reverse()用法及代碼示例
 - Python List copy()用法及代碼示例
 - Python List extend()用法及代碼示例
 - Python Lock acquire()用法及代碼示例
 - Python Lock release()用法及代碼示例
 - Python Lock locked()用法及代碼示例
 - Python numpy.less()用法及代碼示例
 - Python Sympy Permutation.list()用法及代碼示例
 - Python Matplotlib.figure.Figure.subplots_adjust()用法及代碼示例
 - Python numpy.tril()用法及代碼示例
 - Python Matplotlib.pyplot.matshow()用法及代碼示例
 - Python __file__用法及代碼示例
 - Python Pandas Panel.add()用法及代碼示例
 - Python Matplotlib.axis.Tick.get_window_extent()用法及代碼示例
 - Python numpy.fromstring()用法及代碼示例
 
注:本文由純淨天空篩選整理自 Python List index() Method with Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
