python_列表_經常使用操做

  • Python爲提供了一些操做列表的方法

  • 列表的增刪改查操做

序號 分類 關鍵字/函數/方法 說明
1 增長 列表.insert(索引,數據) 在指定位置插入數據
    列表.append(數據) 在末尾追加數據
    列表.extend(列表2) 將列表2的數據追加到列表
2 修改 列表[索引] = 數據 修改指定索引的數據
3 刪除 del列表[索引] 刪除指定索引的數據
    列表.remove[數據] 刪除第一個出現的指定數據
    列表.pop 刪除末尾數據
    列表.pop(索引) 刪除指定索引數據
    列表.clear 清空列表
4 統計 Len(列表) 列表長度
    列表.count(數據) 數據在列表中出現的次數
5 排序 列表.sort() 升序排序
    列表.sort(reverse=True) 降序排序
    列表.reverse() 逆序、反轉

 

 1 #!/usr/bin/env python
 2 # -*- coding: utf-8 -*-
 3 # name_list.append()  name_list.count()   name_list.insert()  name_list.reverse()
 4 # name_list.clear()   name_list.extend()  name_list.pop()     name_list.sort()
 5 # name_list.copy()    name_list.index()   name_list.remove()
 6 
 7 name_list = ["zhangsan","lisi","wangwu"]
 8 # 1.取值和取索引
 9 # print(name_list[3])
10 #IndexError: list index out of range - 列表索引超出範圍
11 print(name_list[2])
12 
13 #知道數據的內容,想肯定數據在列表中的位置
14 #使用index方法須要注意,若是傳遞的數據不在列表中,程序會報錯!
15 print(name_list.index("zhangsan"))
16 
17 # 2.修改
18 # name_list[3] = "lisi"
19 #IndexError: list assignment index out of range - 列表指定的索引超出範圍,程序會報錯
20 name_list[1] = "lisi"
21 
22 # 3.增長
23 #append 方法能夠像列表的末尾追加數據
24 name_list.append("maliu")
25 #insert 方法能夠在列表的指定索引位置插入數據
26 name_list.insert(1,"zhangxiaosan")
27 #extend 方法能夠將其餘列表中的完整內容追加到當前列表的末尾
28 temp_list = ["1","2","3"]
29 name_list.extend(temp_list)
30 
31 # 4.刪除
32 #remove 方法能夠從列表中刪除指定的數據
33 name_list.remove('1')
34 #pop 方法默承認以把列表中最後一個元素刪除
35 name_list.pop()
36 #pop 方法能夠指定要刪除元素的索引
37 name_list.pop(4)
38 #clear 方法能夠清空列表
39 name_list.clear()
40 
41 print(name_list)

 

  •  del 方法

1#!/usr/bin/env python python

 2 # -*- coding: utf-8 -*-
 3 name_list = ["zhangsan","lisi","wangwu"]
 4 #使用 del 關鍵字 (delete)刪除列表元素
 5 #提示:在平常開發中,要從列表刪除數據,建議使用列表提供的方法
 6 del name_list[1]
 7 
 8 #del 關鍵字本質上市用來將一個變量從內存中刪除的
 9 name = "小明"
10 
11 del name
12 #若是使用 del 關鍵字將變量從內存中刪除,後續的代碼就不能再使用這個變量了
13 #NameError: name 'name' is not defined
14 # print(name)
15 
16 print(name_list)

 

  • 列表的統計操做

 1 #!/usr/bin/env python
 2 # -*- coding: utf-8 -*-
 3 name_list = ["張三","李四","王五"]
 4 # len (length 長度)方法能夠統計列表中元素的總數
 5 list_len = len(name_list)
 6 
 7 print("列表中包含 %d 個元素" %list_len)
 8 
 9 #count 方法能夠統計列表中某一個數據出現的次數
10 name_list.append("張三")
11 count= name_list.count("張三")
12 print("張三出現了 %d 次" % count)

 

  • 排序

 1 #!/usr/bin/env python
 2 # -*- coding: utf-8 -*-
 3 name_list = ["zhangsan","lisi","wangwu"]
 4 num_list = [5,6,8,7,0,4,3]
 5 #升序
 6 # name_list.sort()
 7 # num_list.sort()
 8 #降序
 9 # name_list.sort(reverse=True)
10 # num_list.sort(reverse=True)
11 #逆序(反轉)
12 name_list.reverse()
13 num_list.reverse()
14 
15 print(name_list)
16 print(num_list)
相關文章
相關標籤/搜索