1. 程式人生 > >python3列表操作大全 列表操作方法詳解

python3列表操作大全 列表操作方法詳解

添加列 sort return ret odi count reverse lsi 統計

  1 #!/usr/bin/env python
  2 # -*- coding:utf-8 -*-
  3 #Author:SKING
  4 #python3列表操作大全 列表操作方法詳解
  5 
  6 #創建列表
  7 list = [a, b, c, d, e, f]
  8 #取出列表
  9 print(list[0], list[5]) #a f
 10 #列表切片
 11 print(list[1:3]) #[‘b‘, ‘c‘]
 12 print(list[-3:-1]) #[‘d‘, ‘e‘]
 13 #取的時候始終都是按照從左到右的順序進行切片,動作都是顧頭不顧尾。
14 15 #添加列表元素 16 #在最後面添加列表元素 17 list.append(g) 18 print(list) #[‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘, ‘f‘, ‘g‘] 19 #在任意位置插入列表元素 20 list.insert(1, b1) 21 print(list) #[‘a‘, ‘b1‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘, ‘f‘, ‘g‘] 22 #修改列表中的元素 23 list[1] = b2 24 print(list) #[‘a‘, ‘b2‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘, ‘f‘, ‘g‘] 25
#刪除列表中的元素 26 #方法1 刪除指定位置 27 list.remove(b2) 28 print(list) #[‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘, ‘f‘, ‘g‘] 29 #方法2 刪除指定位置 30 del list[1] 31 print(list) #[‘a‘, ‘c‘, ‘d‘, ‘e‘, ‘f‘, ‘g‘] 32 #方法3 33 return_result = list.pop() 34 print(list) #[‘a‘, ‘c‘, ‘d‘, ‘e‘, ‘f‘] 35 #pop()方法是刪除最後一個元素,並返回刪除的元素 36
print(return_result) #g 返回刪除的元素 37 #刪除指定位置 38 list.pop(1) #list.pop(1) = del list[1] 39 print(list) #[‘a‘, ‘d‘, ‘e‘, ‘f‘] 40 41 #列表查找 查找列表元素 42 #查找列表中某一元素所在的位置 43 list = [a, b, c, b, e, b] 44 print(list.index(b)) #1 只能找到第一個 45 print(list[list.index(b)]) #b 46 #統計列表中同一個元素的數量 47 print(list.count(b)) #3 48 #清除列表中的元素 49 list.clear() #沒有返回值 50 print(list) #[] 51 list = [a, b, c, d, e, f] 52 #列表反轉 53 list.reverse() #沒有返回值 54 print(list) #[‘f‘, ‘e‘, ‘d‘, ‘c‘, ‘b‘, ‘a‘] 55 #列表排序 56 list.sort() #默認升序排序 也可以降序排序 sort(reverse=True) 57 print(list) #[‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘, ‘f‘] 58 #排序規則,由大到小依次為:特殊符號 數字 大寫字母 小寫字母 59 #合並列表 60 list_01 = [1, 2, 3, 4] 61 list_02 = [a, b, c, d] 62 list_01.extend(list_02) 63 print(list_01) #[1, 2, 3, 4, ‘a‘, ‘b‘, ‘c‘, ‘d‘] 64 #刪除整個列表 65 del list_02 66 #print(list_02) #NameError: name ‘list_02‘ is not defined 67 68 #列表復制 69 #淺復制 淺copy 僅復制一層 70 #方法1 71 list = [a, b, [c,d], e] 72 list_copy = list[:] 73 print(list_copy) #[‘a‘, ‘b‘, [‘c‘, ‘d‘], ‘e‘] 74 list[2][0] = 11 75 print(list_copy) #[‘a‘, ‘b‘, [11, ‘d‘], ‘e‘] 修改list,list_copy中[11, ‘d‘]也會改變,因為淺復制僅復制了[11, ‘d‘]的地址 76 77 #方法2 78 list = [a, b, [c,d], e] 79 list_copy02 = list.copy() 80 print(list_copy02) #[‘a‘, ‘b‘, [‘c‘, ‘d‘], ‘e‘] 81 list[2][0] = 11 82 print(list_copy02) #[‘a‘, ‘b‘, [11, ‘d‘], ‘e‘] 修改list,list_copy中[11, ‘d‘]也會改變,因為淺復制僅復制了[11, ‘d‘]的地址 83 84 #方法3 85 import copy 86 list = [a, b, [c,d], e] 87 list_copy03 = copy.copy(list) 88 print(list_copy03) #[‘a‘, ‘b‘, [‘c‘, ‘d‘], ‘e‘] 89 list[2][0] = 11 90 print(list_copy03) #[‘a‘, ‘b‘, [11, ‘d‘], ‘e‘] 91 #print(list_copy02) 92 #深復制 深copy 93 import copy 94 list = [a, b, [c,d], e] 95 list_copy04 = copy.deepcopy(list) 96 print(list_copy04) #[‘a‘, ‘b‘, [‘c‘, ‘d‘], ‘e‘] 97 list[2][0] = 11 98 print(list) #[‘a‘, ‘b‘, [11, ‘d‘], ‘e‘] 99 print(list_copy04) #[‘a‘, ‘b‘, [‘c‘, ‘d‘], ‘e‘] 100 #lsit改變了,但是list_copy04卻沒有改變,deepcopy()方法是將list中的所有元素完全克隆了一份給list_copy04

python3列表操作大全 列表操作方法詳解