python 示例_带有示例的Python列表index()方法

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 示例

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值