python序列(三)列表元素访问与计数

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

>>> alist[3]
1
>>> alist[3]=5.5
>>> alist
[1, 3, 5, 5.5, 3, 5, 1, 3, 5]
>>> 
>>> alist[15]
Traceback (most recent call last):
  File "<pyshell#97>", line 1, in <module>
    alist[15]
IndexError: list index out of range

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

>>> alist
[1, 3, 5, 5.5, 3, 5, 1, 3, 5]
>>> alist.index(3)
1
>>> alist.index(100)
Traceback (most recent call last):
  File "<pyshell#102>", line 1, in <module>
    alist.index(100)
ValueError: 100 is not in list

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

>>> alist
[1, 3, 5, 5.5, 3, 5, 1, 3, 5]
>>> alist.count(3)
3
>>> alist.count(5)
3
>>> alist.count(4)
0

 

 
原文地址:https://www.cnblogs.com/wang-yongxu/p/12539877.html