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