发布时间:2022-05-12 09:44:02 人气:193 作者:多测师
使用下标直接访问列表元素,如果指定下标不存在,则抛出异常。
>>> aList[3]
6
>>> aList[3] = 5.5
>>> aList
[3, 4, 5, 5.5, 7, 9, 11, 13, 15, 17]
>>> aList[15]
Traceback (most recent call last):
File "", line 1, in
aList[15]
IndexError: list index out of range
使用列表对象的index()方法获取指定元素首次出现的下标,若列表对象中不存在指定元素,则抛出异常。
>>> aList
[3, 4, 5, 5.5, 7, 9, 11, 13, 15, 17]
>>> aList.index(7)
4
>>> aList.index(100)
Traceback (most recent call last):
File "", line 1, in
aList.index(100)
ValueError: 100 is not in list
使用列表对象的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相关知识,请关注多测师。https://www.e70w.com/xwzx/