Python3學習筆記 | 六、Python的類型與運算-列表
- 2019 年 10 月 6 日
- 筆記
一、列表簡介
列表在Python里是有序集合對象類型,列表裡的對象可以是任何對象:數字,字符串,列表或者之後會講到的字典、元組等等。 與字符串不同,列表是可變對象,支持原處修改的操作。Python中的列表可以完成大多數集合體數據結構的工作,而這些在稍底層一些的語言中你不得不手工去實現。
Python的列表是: • 任意對象的有序集合 • 通過偏移讀取 • 可變長度、異構以及任意嵌套 • 屬於可變序列的分類 • 對象引用數組
二、列表的操作
1、與字符串相同的操作
之前在字符串里的大部分操作都可以用在列表,比如 合併與重複: List1 + List2 : 結果是兩個列表按順序結合。 List1 * 3 : 結果是列表1重複三次。 for i in List1: print i : 按順序打印列表裡的內容 3 in List : 判斷列表裡有沒有一個對象是對象3 List1.index(1) : 查找列表裡第一個為1的對象的位置 List1.count(1): 查找列表裡對象為1的個數 List1[x:y]: 取第x到y的對象,重新建立一個列表 len(List1): List1里的對象個數
2、基本列表操作
創建一個列表:
>>> list1=[1,2,3,4]
對列表內容取值:
>>> list1=[1,2,3,4,5,6,7] >>> list1[6] 7 >>> list1[3:6] [4, 5, 6]
重複:
>>> list1*3 [1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7]
3、列表迭代和解析
使用in方法來判斷:
>>> 7 in list1 True
循環打印列表內容:
>>> for i in list1: ... print(i,end=' ') ... 1 2 3 4 5 6 7
迭代方式創建列表:
>>> list2=[D*3 for D in 'Dora'] >>> list2 ['DDD', 'ooo', 'rrr', 'aaa'] >>> list(map(abs,[-3,-2,-1,0,1,2,3])) [3, 2, 1, 0, 1, 2, 3]
其中map()函數用來返回一個列表,abs則是之前提到了取絕對值
4、索引、分片與矩陣
這個方法和字符串里的方法相似:
>>> list3=['Dora','Emon','DaXiong'] >>> list3[1] 'Emon' >>> list3[0:2] ['Dora', 'Emon'] >>> list3[-3] 'Dora'
矩陣方式:
>>> Dora=[[1,2,3,4],[5,6,7,8],[9,10,11,12]] >>> Dora[2] [9, 10, 11, 12] >>> Dora[2][1]10
5、原處修改
跟字符串不同,列表可以在原處修改:
>>> D=['Dora','Emon'] >>> D ['Dora', 'Emon'] >>> D[2:]=['Da','Xiong'] >>> D ['Dora', 'Emon', 'Da', 'Xiong']
添加元素與排序:
>>> D.append('Jing') >>> D ['Dora', 'Emon', 'Da', 'Xiong', 'Jing'] >>> D.sort() >>> D ['Da', 'Dora', 'Emon', 'Jing', 'Xiong']
三、列表的方法
1、sort、sorted
python中列表的內置函數sort()可以對列表中的元素進行排序,而全局性的sorted()函數則對所有可迭代的序列都是適用的;並且sort()函數是內置函數,會改變當前對象,而sorted()函數只會返回一個排序後的當前對象的副本,而不會改變當前對象。
>>> list4=['Dora','Emon','Da','Xiong'] >>> list4.sort(key=str.lower) >>> list4 ['Da', 'Dora', 'Emon', 'Xiong'] >>> list4.sort(key=str.lower,reverse=True) >>> list4 ['Xiong', 'Emon', 'Dora', 'Da'] >>> >>> list4=['Dora','Emon','Da','Xiong'] >>> sorted(list4) ['Da', 'Dora', 'Emon', 'Xiong'] >>> sorted(list4,key=str.lower,reverse=True) ['Xiong', 'Emon', 'Dora', 'Da'] >>> sorted([x.lower() for x in list4],reverse=True) ['xiong', 'emon', 'dora', 'da']
其中key用來指定排列規則,reverse用來表示是否倒序。
2、extend、pop、reverse
extend()函數用來擴展列表元素,當然列表也支持相加 pop()函數可以默認移除列表最後一個元素的效果,也可對指定位置進行移除 reverse()函數則使列表倒序
>>> list5=['Dora','Emon','Da','Xiong'] >>> list5.extend(['Jing','Xiang']) >>> list5 ['Dora', 'Emon', 'Da', 'Xiong', 'Jing', 'Xiang'] >>> list5.pop()'Xiang' >>> list5 ['Dora', 'Emon', 'Da', 'Xiong', 'Jing'] >>> list5.pop(2)'Da' >>> list5 ['Dora', 'Emon', 'Xiong', 'Jing'] >>> list5.reverse() >>> list5 ['Jing', 'Xiong', 'Emon', 'Dora']
3、index、insert、del
index()函數用來返回元素位置 insert()函數用來對指定位置進行插入元素 sel則是刪除指定位置元素
>>> list6=['Dora','Emon','Da','Xiong'] >>> list6.index('Da') 2 >>> list6.insert(4,'Jing') >>> list6 ['Dora', 'Emon', 'Da', 'Xiong', 'Jing'] >>> del list6[4] >>> list6 ['Dora', 'Emon', 'Da', 'Xiong'] >>> del list6[0:] >>> list6 []
四、實際用法
1、取值
當一個列表裡的內容是有固定含義時,比如:[『姓名』, 年齡,[出生年,月,日]],像是這樣:[『Dora』,77,[1942,6,4]]
>>> info=['Dora',77,[1942,6,4]] >>> name,age,brith=info >>> print(str(name)+str(age)+str(brith)) Dora77[1942, 6, 4] >>> name,age,(brith_y,brith_m,brith_d)=info >>> print(str(name)+str(age)+str(brith_y)+str(brith_m)+str(brith_d)) Dora77194264
當一個列表長度不固定,比如: [『Abby』,』[email protected]』,』111-222-333』,』111-222-222』] [『Bobby』,』[email protected]』,』111-333-333』] 這時候就可以使用*代表多個元素
>>> A_name, A_mail, *A_phone = ['Abby','[email protected]','111-222-333','111-222-222'] >>> B_name, B_mail, *B_phone = ['Bobby', '[email protected]', '111-333-333'] >>> print(A_name, A_mail, A_phone) Abby [email protected] ['111-222-333', '111-222-222'] >>> print(B_name, B_mail, B_phone) Bobby [email protected] ['111-333-333']
只保留列表裡最後N個記錄: 使用deque模塊限定數組最大長度,並且有新元素添加的時候,數組整體將左移或右移。
>>> from collections import deque >>> q = deque(maxlen=3) >>> q.append('a') >>> q.append('b') >>> q.append('c') >>> q deque(['a', 'b', 'c'], maxlen=3) >>> q.append('d') >>> q deque(['b', 'c', 'd'], maxlen=3) >>> q.appendleft('e') >>> q deque(['e', 'b', 'c'], maxlen=3) >>> q.pop()'c' >>> q deque(['e', 'b'], maxlen=3)
2、查找最大,最小值
查找最大值最小值可以直接使用max與min,但是想要獲取幾個最大或者最小的數就需要用到nlargest與nsmallest了。
>>> nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2] >>> max(nums) 42 >>> min(nums) -4 >>> sum(nums) 159 >>> >>> from heapq import nlargest, nsmallest >>> nlargest(3,nums) [42, 37, 23] >>> nsmallest(3,nums) [-4, 1, 2]
3、命名切片
之前切片都是使用nums[0:2]的方式,其實也可以使用slice函數來具體定義切片的名稱,但是以下操作在python3中並沒有實現,python2可以正常使用。
>>> nums = [0,1,2,3,4,5,6] >>> _slice1 = slice(0,2) >>> _slice2 = slice(2,4) >>> _slice3 = slice(3,7) >>> nums[_slice1] [0, 1] >>> nums[_slice2] [2, 3] >>> nums[_slice3] [3, 4, 5, 6]
4、重複的元素計算
collections里的Counter模塊可以計算列表裡重複元素的個數:
>>> from collections import Counter >>> words = ['look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes', ... 'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the', ... 'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into', ... 'my', 'eyes', "you're", 'under'] >>> countered_words = Counter(words) >>> countered_words Counter({'eyes': 8, 'the': 5, 'look': 4, 'into': 3, 'my': 3, 'around': 2, "you're": 1, "don't": 1, 'under': 1, 'not': 1}) >>> countered_words.most_common(2) [('eyes', 8), ('the', 5)] >>> morewords = ['why','are','you','not','looking','in','my','eyes'] >>> countered_words.update(morewords) >>> countered_words Counter({'eyes': 9, 'the': 5, 'look': 4, 'my': 4, 'into': 3, 'not': 2, 'around': 2, "you're": 1, "don't": 1, 'in': 1, 'you': 1, 'looking': 1, 'are': 1, 'under': 1, 'why': 1})