在使用Python的過程中,一定是離不開數據結構的, 也就是List-列表,Tuples-元組,Dictionaries-字典。
那實際應用中我們更多的還是要去操作這些結構里的數據。比如,在列表后面添加元素,那么就會用到append() 方法。
那除了這些本身的操作方法之外,還有一個Python內建模塊——collections,也提供了不少使用的方法,今天來捋一下。
一、Counter
這是一個計數器,我們可以用來方便的統計出一些元素出現的次數,比如String、List、Tuples等等。
String
1
2
3
4
5
6
7
8
|
from collections import Counter c = Counter( "HelloKitty" ) print (c) #運行結果: Counter({ 'l' : 2 , 't' : 2 , 'H' : 1 , 'e' : 1 , 'o' : 1 , 'K' : 1 , 'i' : 1 , 'y' : 1 }) |
List
1
2
3
4
5
6
7
8
|
from collections import Counter c = Counter([ "蘋果" , "櫻桃" , 1 , 1 , 4 , 4 , 5 ]) print (c) #運行結果: Counter({ 1 : 2 , 4 : 2 , '蘋果' : 1 , '櫻桃' : 1 , 5 : 1 }) |
二、deque
我們很喜歡用list來存放數據,因為非常的方便。但是list的缺點也很明顯,如果你是按索引訪問元素就很快,但是插入和刪除元素就很慢。
當然了,數據量小的時候肯定是感知不到的,只有當數據量大的時候,你才會發現這個缺點,因為list是線性數據結構,比如插入這個動作,需要把它后面的元素都挪一位。
deque除了實現list的append()和pop()外,還提供了appendleft()和popleft(),這樣的話我們可以很方便的向著列表的另一頭,進行添加和移除操作了。
1
2
3
4
5
6
7
8
9
10
|
from collections import deque deque_list = deque([ 'a' , 'b' , 'c' , 'd' ]) deque_list.append( '蘋果' ) deque_list.appendleft( '吃' ) print (deque_list) #運行結果: deque([ '吃' , 'a' , 'b' , 'c' , 'd' , '蘋果' ]) |
三、OrderedDict
使用Python,大家自然知道Dict字典中的key是無序的。那如果你想要保持key的順序的話,用OrderedDict即可。
1
2
3
4
5
6
7
8
9
10
11
|
from collections import OrderedDict list_a = [( 1 , "蘋果" ), ( 2 , "香蕉" ), ( 3 , "西瓜" ), ( 4 , "芒果" )] order_dict = OrderedDict(list_a) print (order_dict) #運行結果: D:\Daily λ python whatiscollections.py OrderedDict([( 1 , '蘋果' ), ( 2 , '香蕉' ), ( 3 , '西瓜' ), ( 4 , '芒果' )]) |
如果有場景中需要使用到,可以試試這幾種用法。
以上就是了解一下python內建模塊collections的詳細內容,更多關于python collections的資料請關注服務器之家其它相關文章!
原文鏈接:https://www.cnblogs.com/pingguo-softwaretesting/p/13085819.html