使用下標(biāo)直接訪問(wèn)列表元素,如果指定下標(biāo)不存在,則拋出異常。
>>>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
使用列表對(duì)象的index()方法獲取指定元素首次出現(xiàn)的下標(biāo),若列表對(duì)象中不存在指定元素,則拋出異常。
>>>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
使用列表對(duì)象的count()方法統(tǒng)計(jì)指定元素在列表對(duì)象中出現(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列表元素訪問(wèn)與計(jì)數(shù),希望對(duì)大家有所幫助,如果想要了解更多Python相關(guān)知識(shí),請(qǐng)關(guān)注IT培訓(xùn)機(jī)構(gòu):千鋒教育。