1. 程式人生 > >python之列表方法

python之列表方法

列表方法

一、呼叫方法:

object.method(arguements)

方法呼叫與函式呼叫很像,只是在方法名前加上物件和句號。

1.append

定義:將一個物件附加到列表末尾

函式:lst.append(char)

程式碼:

1 lst = [1,2,3]
2 lst.append(4)
3 print(lst)

結果:

1 [1, 2, 3, 4]

 

2.clear

定義:清除列表內容

函式:lst.clear()

程式碼:

1 lst = [1,2,3]
2 lst.clear()
3 print(lst)

結果:

1 []

 

3.copy

定義:複製列表;複製成一個新列表後,再進行對新列表進行操作,不會影響到原列表

函式:lst.copy

程式碼:

1 lst = [1,2,3]
2 lst_1 = lst.copy()  #copy操作
3 lst_1.append(5) #在copy的列表中增加5
4 print(lst)
5 print(lst_1)

結果:

1 [1, 2, 3]
2 [1, 2, 3, 5]

 

4.count

定義:計算列表中元素出現的次數

函式:lst.count(char)

程式碼:

1
lst = [1,2,3,4,4,4,4,4,4,44,4,4,4,4,4,4,4,4,4,4,4,4] 2 lst_1 = lst.count(4) 3 print(lst_1)

結果:

1 18

 

5.extend

定義:將一個列表中元素拓展到另一個列表中

函式:lst.extend(lst1)

程式碼:

1 lst = [1,2,3,4,4,4,4,4,4,44,4,4,4,4,4,4,4,4,4,4,4,4]
2 lst_2 = ['java',1,4,5,'looo','python']
3 lst.extend(lst_2)
4 print
(lst)

 

結果

1 [1, 2, 3, 4, 4, 4, 4, 4, 4, 44, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 'java', 1, 4, 5, 'looo', 'python']

 

6.index

定義:查詢列表中的元素,並返回其元素的索引位置

函式:lst.index(char)

程式碼:

1 lst = [1,2,3,'java',1,4,5,'looo','python']
2 lst_1 = lst.index('python')
3 print(lst_1)

結果:

8

 

7.insert

定義:在列表中插入物件,插入方式是通過索引來增加元素

函式:lst.insert(索引,‘char’)

程式碼:

1 lst = [1,2,3,'java',1,4,5,'looo','python']
2 lst.insert(3,'LOL')
3 print(lst)

結果:

1 [1, 2, 3, 'LOL', 'java', 1, 4, 5, 'looo', 'python']

 

8.pop

定義:移除列表中的最後一個元素

函式:lst.pop()

程式碼:

1 lst = [1,2,3,'java',1,4,5,'looo','python']
2 lst.pop()
3 print(lst)

結果:

1 [1, 2, 3, 'java', 1, 4, 5, 'looo']

 

9.remove

定義:移除列表中指定的元素

函式:lst.remove(‘元素’)

程式碼:

1 lst = [1,2,3,'java',1,4,5,'looo','python']
2 lst.remove(1)
3 print(lst)

結果:

1 [2, 3, 'java', 1, 4, 5, 'looo', 'python']

10.reverse

定義:對列表進行反向排序

函式:lst.reverse()

程式碼:

1 lst = [1,2,3,'java',1,4,5,'looo','python']
2 lst.reverse()
3 print(lst)

結果:

1 ['python', 'looo', 5, 4, 1, 'java', 3, 2, 1]

 

11.sort

定義:對列表進行就地排序

函式:lst.sort()

程式碼:

1 lst = [4,6,2,1,90,66,6]
2 lst.sort()
3 print(lst)

結果:

1 [1, 2, 4, 6, 6, 66, 90]