python 列表元素访问与计数

2023-12-13 9:29:12 网络知识 匿名

使用下标直接访问列表元素,如果指定下标不存在,则抛出异常。

>>>aList[3]

6

>>>aList[3]=5.5

>>>aList

[3,4,5,5.5,7,9,11,13,15,17]

>>>aList[15]

Traceback(mostrecentcalllast):

File"",line1,in

aList[15]

IndexError:listindexoutofrange

使用列表对象的index()方法获取指定元素首次出现的下标,若列表对象中不存在指定元素,则抛出异常。

>>>aList

[3,4,5,5.5,7,9,11,13,15,17]

>>>aList.index(7)

4

>>>aList.index(100)

Traceback(mostrecentcalllast):

File"",line1,in

aList.index(100)

ValueError:100isnotinlist

使用列表对象的count()方法统计指定元素在列表对象中出现的次数。

>>>aList

[3,4,5,5.5,7,9,11,13,15,17]

>>>aList.count(7)

1

>>>aList.count(0)

0

>>>aList.count(8)

0

以上内容为大家介绍了python列表元素访问与计数,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注IT培训机构:瀚银百科。

发表评论: