Python使用list一、list
Python內置的一種數據類型是列表:list。list是一種有序的集合,可以隨時添加和刪除其中的元素。
比如,列出班里所有同學的名字,就可以用一個list表示:
classmates = ['Michael', 'Bob', 'Tracy']print(classmates)
變量classmates就是一個list。
len()函數1. 獲得list元素的個數: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])
以此類推,可以獲取倒數第2個、倒數第3個:
classmates = ['Michael', 'Bob', 'Tracy']
print(classmates[-1])
print(classmates[-2])
print(classmates[-3])
print(classmates[-4])
當然,倒數第4個就越界了。
2. list是一個可變的有序表,往list中追加元素到末尾:classmates = ['Michael', 'Bob', 'Tracy']
classmates.append('Adam')
print(classmates)
也可以把元素插入到指定的位置,比如索引號為1的位置:
classmates = ['Michael', 'Bob', 'Tracy']#替換classmates.insert(1, 'Jack')
print(classmates)
pop()函數1. 刪除list末尾的元素classmates = ['Michael', 'Bob', 'Tracy']
print(classmates.pop())
print( classmates)['Michael', 'Jack', 'Bob', 'Tracy']
2. 刪除指定位置的元素,用pop(i)方法,其中i是索引位置。
classmates.pop(1)
print(classmates)
3. 把某個元素替換成別的元素,可以直接賦值給對應的索引位置:
classmates = ['Michael', 'Bob', 'Tracy']
classmates[1] = 'Sarah'
print(classmates)
list里面的元素的數據類型也可以不同,比如:
L = ['Apple', 123, True]
list元素也可以是另一個list,比如:
s = ['python', 'java', ['asp', 'php'], 'scheme']print(len(s))
要注意s只有4個元素,其中s[2]又是一個list,如果拆開寫就更容易理解了:
p = ['asp', 'php']s = ['python', 'java', p, 'scheme']
要拿到'php'可以寫p[1]或者s[2][1],因此s可以看成是一個二維數組,類似的還有三維、四維……數組,不過很少用到。
如果一個list中一個元素也沒有,就是一個空的list,它的長度為0:
L = []len(L)二、總結
本文基于Python基礎,主要介紹了Python基礎中list列表,通過list列表的兩個函數 ,對list的語法做了詳細的講解,用豐富的案例 ,代碼效果圖的展示幫助大家更好理解 。
使用Python編程語言,方便大家更好理解,希望對大家的學習有幫助。
-
可編程邏輯
+關注
關注
7文章
523瀏覽量
44457 -
python
+關注
關注
56文章
4821瀏覽量
85776
發布評論請先 登錄
相關推薦
Python中的迭代器與生成器
對比Python與Java編程語言
圖紙模板中的文本變量

Python建模算法與應用
Win10 vscode中無法編譯,提示python.exe: command not found怎么解決?
逆變器的常見類型及其特點分析
嵌入式中C語言結構體基本實現

OpenHarmony語言基礎類庫【@ohos.util.List (線性容器List)】

評論