Python元组索引()

时间:2020-02-23 14:43:37  来源:igfitidea点击:

在本教程中,我们将看到Python元组的索引方法.Python元组索引方法用于在元组中查找元素的索引

Python元组index语法

tuple1.index(element)

Tuple1是元组和元素的对象是我们想要获取索引的对象。

Python元组index示例

Python元组索引方法用于查找元素中的元素索引。
如果元组不存在,那么它将提高ValueError。
让我们了解索引方法。

tupleOfCounties=('China','Netherlands','USA','Bhutan')
print("Index of USA in tupleOfCounties:",tupleOfCounties.index('USA'))

输出:

Index of USA in tupleOfCounties: 2

如果元组中不存在元素,则它将提高valueError。

tupleOfCounties=('China','Netherlands','USA','Bhutan')
print("Index of Nepal in tupleOfCounties:",tupleOfCounties.index('Nepal'))

输出:

—————————————————————————
ValueError                                Traceback (most recent call last)
 in ()
      1 tupleOfCounties=('China','Netherlands','USA','Bhutan')
—-> 2 print(“Index of USA in tupleOfCounties:",tupleOfCounties.index('Nepal'))
      3 
<!-- /8691100/theitroad_S2S_Leaderboard_ROS_InContent -->

valueError:tuple.index(x):x不是元组

如果列表中有多个元素出现,则索引方法将返回第一次出现。

tupleOfCounties=('China','Netherlands','USA','Bhutan','Netherlands')
print("Index of Netherlands in tupleOfCounties:",tupleOfCounties.index('Netherlands'))

输出:

Index of Netherlands in tupleOfCounties: 1