Python基礎(chǔ)變量類型——List淺析

Python使用list

一、list

Python內(nèi)置的一種數(shù)據(jù)類型是列表:list。list是一種有序的集合,可以隨時添加和刪除其中的元素。

比如,列出班里所有同學(xué)的名字,就可以用一個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個就越界了。

12下一頁>

(免責聲明:本網(wǎng)站內(nèi)容主要來自原創(chuàng)、合作伙伴供稿和第三方自媒體作者投稿,凡在本網(wǎng)站出現(xiàn)的信息,均僅供參考。本網(wǎng)站將盡力確保所提供信息的準確性及可靠性,但不保證有關(guān)資料的準確性及可靠性,讀者在使用前請進一步核實,并對任何自主決定的行為負責。本網(wǎng)站對有關(guān)資料所引致的錯誤、不確或遺漏,概不負任何法律責任。
任何單位或個人認為本網(wǎng)站中的網(wǎng)頁或鏈接內(nèi)容可能涉嫌侵犯其知識產(chǎn)權(quán)或存在不實內(nèi)容時,應(yīng)及時向本網(wǎng)站提出書面權(quán)利通知或不實情況說明,并提供身份證明、權(quán)屬證明及詳細侵權(quán)或不實情況證明。本網(wǎng)站在收到上述法律文件后,將會依法盡快聯(lián)系相關(guān)文章源頭核實,溝通刪除相關(guān)內(nèi)容或斷開相關(guān)鏈接。 )

贊助商
2020-07-21
Python基礎(chǔ)變量類型——List淺析
Python使用list一、listPython內(nèi)置的一種數(shù)據(jù)類型是列表:list。list是一種有序的集合,可以隨時添加和刪除其中的元素。

長按掃碼 閱讀全文