作者博文地址:https://www.cnblogs.com/liu-shuai/
列表是Python中最基本的數據結構,是Python最常用的數據類型。Python列表是任意對象的有序集合,通過索引訪問指定元素,第一個索引是0,第二個索引是1,依此類推。列表可變對象,支持異構、任意嵌套。
創建一個列表
list1 = [] #創建空列表
list2 = ['a','b','c','d','e']
list3 = ['a','b','c',1,2,3]
列表支持的操作方法及實例展示
可以使用dir(list)查看列表支持的所有操作
append
1 功能:列表添加元素,添加至列表末尾 2 語法: L.append(object) -- append object to end 3 L = ['a','c','b','d'] 4 L.append('e') 5 結果:L 6 ['a','c','b','d','e']
7 l = [1,2,3]
8 L.append(l)
9 結果:L
10['a','c','b','d',[1,2,3]]
count
1 功能:統計指定元素在列表中的個數 2 語法: L.count(value) -> integer -- return number of occurrences of value 3 L = [1,2,3,4,5,5] 4 L.count(5) 5 結果:2 6 l = [1,2,3,4,5,[5,6]] 7 l.count(5) 8 結果:1 #只統計第一層的元素個數
extend
1 功能:迭代字符元素或列表元素 2 語法: L.extend(iterable) -- extend list by appending elements from the iterable 3 L= ['a','b','c','d'] 4 l = [1,2,3] 5 L.extend('e') 6 結果:L 7 ['a','b','c','d','e'] 8 L.extend(l) #注意與append的區別 9 結果:L 10 ['a','b','c','d',1,2,3]
index
1 功能:定位列表中的指定元素 2 語法: L.index(value, [start, [stop]]) -> integer -- return first index of value. Raises ValueError if the value is not present. 3 L = ['a','b','c','d'] 4 L.index('c') 5 結果:2 6 L.index('f') 7 結果:Traceback (most recent call last): 8 File "<stdin>", line 1, in <module> 9 ValueError: 'f' is not in list
insert
1 功能:在指定索引位置的元素前面插入新的元素 2 語法:L.insert(index, object) -- insert object before index 3 L = ['a','b','c','d'] 4 L.insert(2,'e') 5 結果:L 6 ['a','b','e','c','d']
pop
1 功能:刪除指定索引值的元素,返回值為當前刪除的元素的值。不指定索引值,默認刪除最后一個元素 2 語法:L.pop([index]) -> item -- remove and return item at index (default last). Raises IndexError if list is empty or index is out of range. 3 L = ['a','b','c','d'] 4 L.pop() 5 結果:'d' 6 L.pop(2) 7 結果:'c'
remove
1 功能:刪除列表中指定的元素 2 語法:L.remove(value) -- remove first occurrence of value. Raises ValueError if the value is not present. 3 L = ['a','b','c','d'] 4 L.remove('c') 5 結果:print L 6 ['a','b','d']
reverse
1 功能:用於反向列表中的元素 2 語法:L.reverse() -- reverse *IN PLACE* 3 L = ['a','b','c','d'] 4 L.reverse() 5 結果:print L 6 ['d','c','b','a']
sort
1 功能:對列表中的元素進行排序。 2 語法:L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*; cmp(x, y) -> -1, 0, 1 3 L = ['d','b',1,2,3,'a','d'] 4 L.sort() 5 結果:print L 6 [1,2,3,'a','b','c','d'] 7 8 L = ['d','b',1,2,3,'a','d',['ab','bc']] 9 L.sort() 10 結果:print L 11 [1, 2, 3, ['ab', 'bc'], 'a', 'b', 'd', 'd']
L1 + L2
1 功能:合並兩個列表,返回一個新的列表,原列表不變 2 語法:L = L1 + L2 -> list 3 L1 = ['a','b','c'] 4 L2 = [1,2,3] 5 L = L1 + L2 6 結果: 7 print L 8 ['a','b','c',1,2,3] 9 print L1 10 ['a','b','c'] 11 print L2 12 [1,2,3]
L * n
1 功能:重復輸出列表n次,返回一個新列表,原列表不變 2 語法:L = L1 * n 3 L1 = ['a','b','c','d'] 4 L = L1 * 3 5 結果: 6 print L 7 ['a','b','c','d','a','b','c','d','a','b','c','d'] 8 print L1 9 ['a','b','c','d']