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

 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM