Python中list列表的常見操作

Python的list是一個列表,用方括號包圍,不同元素間用逗號分隔。

列表的數據項不需要具有相同的類型。(列表還可以嵌套,即列表中的列表)

每個元素都有一個索引(表示位置),從0開始;可以用索引-1表示最後一個元素,-2表示倒數第二個元素。

(1)獲取列表長度,用len( ) 方法:

list1 = [ 1, 2 , 3, 4]
print( len(list1) );   #  4

(2)刪除列表元素,用索引找列表元素:

list1 = [1,2,3,4,5,6,7,8,9,10]
del list1[2] # 或del list[2]
print(list1) # [1, 2, 4, 5, 6, 7, 8, 9, 10]
print(list1[1:-1]) # [2, 4, 5, 6, 7, 8, 9]

(3)迭代和遍歷:

list1 = [ 1, 2 , 3, 4]
for x in list1:
    print(x) 

遍歷 [start,end),間隔為 span,當 span>0 時順序遍歷, 當 span<0 時,逆着遍歷。
start 不輸入則默認為 0,end 不輸入默認為長度。

list = [i for i in range(0,15)]
print(list) #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
print(list[::2]) #[0, 2, 4, 6, 8, 10, 12, 14]

(4)加號和乘號:+ 號用於組合列表,* 號用於重複列表。也支持+=或*=運算符

list1 = [ 1, 2, 3, 4]
list2 = [ 5, 6, 7, 8]
list = list1 + list2
print(list);  # [1,2,3,4,5,6,7,8]
print(list1*2); #[1,2,3,4,1,2,3,4]

(5)合併列表 (除了+外),還有append( )和extend( )方法,
注意區別,append( )是將列表整體作為一個元素加入,extend( )是把列表每個元素加入;
兩者都會直接修改原列表list1數據

list1 = [ 1, 2, 3, 4]
list2 = [ 5, 6, 7, 8]
list1.append(list2)
print(list1) #[1, 2, 3, 4, [5, 6, 7, 8]]

list1 = [ 1, 2, 3, 4]
list2 = [ 5, 6, 7, 8]
list1.extend(list2)
print(list1) #[1, 2, 3, 4, 5, 6, 7, 8]

還有一種插入列表的方法,叫切片,可以指定插入位置:

aList = [1,2,3,4]
bList = ['www', 'pythontab.com']
aList[1:1] = bList
print(aList) #[1, 'www', 'pythontab.com', 2, 3, 4]

(6)Python的以下函數可用於列表:

min(list) 求最大值
max(list) 求最小值
list(seq) 將元組轉換為列表

(7)list的其他方法:

list.count(obj) 統計某個元素在列表中出現的次數
list.reverse()  反向列表中元素
list.index(obj) 從列表中找出某個值第一個匹配項的索引位置
list.insert(index, obj)  將對象按位置插入列表
list.pop([index=-1])  移除列表中的一個元素(默認最後一個元素),並且返回該元素的值
list.remove(obj)  移除列表中某個值的第一個匹配項,在原列表上刪除。
list.sort(key=None, reverse=False) 對原列表進行排序
list.clear() 清空列表
list.copy()  複製列表

(8)創建二維列表
例如,3行5列的二維列表

list_2d = [[col for col in range(5)] for row in range(3)]
print(list_2d) #[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]]

(9)列表推導式:
例如:
squares = [x**2 for x in range(10)]

會生成[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]的列表

(10) 列表的切片表示
形式是
[ startIndex : endIndex : step ]

索引為0或不寫表示第一個元素,索引可以為-1表示最後一個元素,索引為end或不寫表示最後一個元素加一,step為-1表示反向走。

結果中包含startIndex元素,不包含endIndex元素。

因此 list1[::-1]可以表示list1的反序。

特別的,list1[:]仍表示list1自己。

Python中的字符串也可以使用切片表示。

更詳細的,可以參考Python官方文檔
//docs.python.org/zh-cn/3.7/tutorial/datastructures.html#list-comprehensions

Tags: