使用下標直接訪問列表元素,如果指定下標不存在,則拋出異常。
>>>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()方法獲取指定元素首次出現(xiàn)的下標,若列表對象中不存在指定元素,則拋出異常。
>>>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()方法統(tǒng)計指定元素在列表對象中出現(xiàn)的次數(shù)。
>>>aList
[3,4,5,5.5,7,9,11,13,15,17]
>>>aList.count(7)
1
>>>aList.count(0)
0
>>>aList.count(8)
0
以上內(nèi)容為大家介紹了python列表元素訪問與計數(shù),希望對大家有所幫助,如果想要了解更多Python相關(guān)知識,請關(guān)注IT培訓(xùn)機構(gòu):千鋒教育。