python 示例
列出index()方法 (List index() Method)
index() method is used to get the index of the specified element, the method is called with this list and element can be supplied as an argument, it returns the index of the first occurrence of the element in the list.
index()方法用于获取指定元素的索引,该方法与此列表一起调用,并且元素可以作为参数提供,它返回列表中元素首次出现的索引。
Syntax:
句法:
list_name.index(element)
Parameter(s):
参数:
element – It represents an element whose index to be found.
element –它表示要查找其索引的元素。
Return value:
返回值:
The return type of this method is <class 'int'>, it returns an integer element that will the index of the first occurrence of the element, or it returns a ValueError if element does not exist in the list.
此方法的返回类型为<class'int'> ,它返回一个整数元素,该元素将是该元素首次出现的索引,或者如果列表中不存在element,则返回ValueError 。
Example 1:
范例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)
Output
输出量
cars: ['Porsche', 'Audi', 'Lexus', 'Porsche', 'Audi']
Porsche's index is: 0
Lexus's index is: 2
Example 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"))
Output
输出量
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
翻译自: https://www.includehelp.com/python/list-index-method-with-example.aspx
python 示例