Python基礎(chǔ)變量類型——List淺析
Python使用list
一、list
Python內(nèi)置的一種數(shù)據(jù)類型是列表:list。list是一種有序的集合,可以隨時添加和刪除其中的元素。
比如,列出班里所有同學的名字,就可以用一個list表示:
classmates = ['Michael', 'Bob', 'Tracy']print(classmates)
變量classmates就是一個list。
len()函數(shù)1. 獲得list元素的個數(shù):classmates = ['Michael', 'Bob', 'Tracy']print(len(classmates))
用索引來訪問list中每一個位置的元素,記得索引是從0開始的:
classmates = ['Michael', 'Bob', 'Tracy']
print(classmates[0])
print(classmates[1])
print(classmates[2])
print(classmates[3])
當索引超出了范圍時,Python會報一個IndexError錯誤,所以,要確保索引不要越界,記得最后一個元素的索引是len(classmates) - 1。
如果要取最后一個元素,除了計算索引位置外,還可以用-1做索引,直接獲取最后一個元素:
print(classmates[-1])
以此類推,可以獲取倒數(shù)第2個、倒數(shù)第3個:
classmates = ['Michael', 'Bob', 'Tracy']
print(classmates[-1])
print(classmates[-2])
print(classmates[-3])
print(classmates[-4])
當然,倒數(shù)第4個就越界了。

請輸入評論內(nèi)容...
請輸入評論/評論長度6~500個字
最新活動更多
-
7月8日立即報名>> 【在線會議】英飛凌新一代智能照明方案賦能綠色建筑與工業(yè)互聯(lián)
-
7月22-29日立即報名>> 【線下論壇】第三屆安富利汽車生態(tài)圈峰會
-
7.30-8.1火熱報名中>> 全數(shù)會2025(第六屆)機器人及智能工廠展
-
7月31日免費預約>> OFweek 2025具身智能機器人產(chǎn)業(yè)技術(shù)創(chuàng)新應用論壇
-
免費參會立即報名>> 7月30日- 8月1日 2025全數(shù)會工業(yè)芯片與傳感儀表展
-
即日-2025.8.1立即下載>> 《2024智能制造產(chǎn)業(yè)高端化、智能化、綠色化發(fā)展藍皮書》
推薦專題