4種非常實用的python內置數據結構
Python不僅僅可以使用內置的list實現數組,還支持像C語言那樣的指定類型的原生數組array。很顯然,因為list可以存儲各種類型的對象,而array只存儲一個指定的原生類型,所以當數據量較大時,原生array在內存占用方面要比list小。而且array不像C語言里那樣在定義時就限制了大小,它支持list所支持的各種常用函數。相比之下Python的array更像是C++的vector。
from array import arrayl = list(range(100))a = array.fromlist(l)print(l.__sizeof__(), a.__sizeof__())
目前array有兩個限制。首先,它只支持整數、小數、unicode字符,而不能像C++的vector那樣支持多種數據類型。另外目前指定類型比較麻煩,我們需要使用類型對應的字母縮寫來指定,而不能使用簡單的諸如int,float的方式。
a = array(’i’)a.append(1)a.append(4)Type code C Type Python Type Minimum size in bytes ’b’ signed char int 1 ’B’ unsigned char int 1 ’u’ wchar_t Unicode character 2 ’h’ signed short int 2 ’H’ unsigned short int 2 ’i’ signed int int 2 ’I’ unsigned int int 2 ’l’ signed long int 4 ’L’ unsigned long int 4
更詳細的信息可以參考:https://docs.python.org/3.8/library/array.html
defaultdictC++的map對于新的key會自動使用value type的默認構造函數構造一個值,而Python默認的dict對于不存在的key的訪問會拋出異常(賦值除外)。這是因為Python不知道value的類型,所以沒辦法為我們默認構造。defaultdict要求我們在構造時指定一個類型,然后會自動根據需要初始化value。這樣我們就可以使用簡單的代碼來實現很多功能。
下面的代碼,我對比了使用defaultdict和original dict實現將學生按照姓的首字母分組的功能,以及分類計數的功能。
import collectionsstudents = [’Zhang San’, ’Li Si’, ’Zhou liu’, ’Chen qi’, ’Cheng ba’]# using defaultdictdd = collections.defaultdict(list)for s in students:key = s[0]dd[key].append(s)print(dd)# using original dict (method 1)od = {}for s in students:key = s[0]if key not in do:od[key] = []od[key].append(s)print(od)scores = [’A’, ’B’, ’C’, ’A’, ’A’, ’B’, ’C’, ’B’, ’A’, ’A’]# using defaultdictdd = collections.defaultdict(int)for s in scores :dd[s] += 1print(dd)# using original dict (method 2)od = collections.defaultdict(int)for s in scores :if s not in do:do[s] = 1else:do[s] += 1print(od)Named Tuple
編程實踐中我們經常需要創建一些小的數據結構用來整合一組相關聯的數據,簡單的比如地理坐標的經緯度,顏色的RGB值或者矩形框的左上和右下坐標,復雜的比如構造一個窗口的一組參數。實踐中,我們通常有3中實現方法:
對每一個這樣的數據結構創建一個class。優點是可以直接使用名字訪問數據成員,而且支持復雜的訪問邏輯和數據操作。缺點是需要編寫對應的類和必須的函數,管理文件和引用關系。 使用tuple。優點是編寫簡單,內存使用效率高。缺點是只能使用下標訪問,可讀性差,容易出錯。 使用dict,用str來作為對于屬性的名字。優點是編寫相對簡單,而且保留了變量的名字。缺點是需要使用字符串表示名字較為麻煩,而且每一個結構都要保存作為名字的字符串,浪費空間。collections的nametuple可以為我們直接構造一個具有名字的簡單類型,方便快捷地實現類似手寫了一個class的效果。需要注意的是collections.nametuple是一個factory function,它用來幫我們創建一個類型,而不是這個類型的具體對象。創建類型時,我們可以指定各個屬性的名字,之后就可以使用.來訪問了,而且它同時還支持使用下標訪問。同時Named Tuple還支持_asdict函數用來將內部的數值轉換成一個dict。
# classclass Rect:def __init__(self, x1, y1, x2, y2):self.x1 = x1self.y1 = y1self.x2 = x2self.y2 = y2def area_class(r):w = r.x2 - r.x1h = r.y2 - r.y1return w*hr1 = Rect(1,3,5,5)# <__main__.Rect object at 0x7fde252a87f0># to show its content, we need to implement __repr__(self) or __str__(self)print(area_class(r1))# tupledef area_tuple(r):w = r[2]-r[0]h = r[3]-r[1]return w*hr2 = (1,3,5,5)print(r2)# (1, 3, 5, 5)print(area_tuple(r2))# dictdef area_dict(r):w = r['x2'] - r['x1']h = r['y2'] - r['y1']return w*hr3 = {'x1':1, 'y1':3, 'x2':5, 'y2':5}print(r3)# {’x1’: 1, ’y1’: 3, ’x2’: 5, ’y2’: 5}print(area_tuple(r3))# named tupleimport collectionsRectangle = collections.namedtuple('Rectangle', ['x1', 'y1', 'x2', 'y2'])def area_namedtuple(r):w = r.x2 - r.x1y = r.y2 - r.y1return w*hr4 = Rectangle(1,3,5,5)print(r4)# Rectangle(x1=1, y1=3, x2=5, y2=5)x1,y2,x2,y2 = r4print(x1,y2,x2,y2)# 1 3 5 5print(area_namedtuple(r4))print(area_class(r4)) # work with '.' grammarprint(area_tuple(r4)) # work with indexprint(area_dict(r4._asdict())) # work with dictCounter
顧名思義,Counter是用來對元素進行計數的,它也是collections這個包里的。根據Python的官方文檔,它是dict類型的一個子類。在構造的時候輸入一個iterable的類型,比如list,range或是一個mapping的類型,比如dict,defaultdict。然后Counter就會對其中的元素進行計數。比較特殊的是,Counter對負數沒有做特殊處理,就是說在特殊操作下允許出現測試為負,后面我們會有例子。
c = Counter() # a new, empty counterc = Counter(’gallahad’) # a new counter from an iterableprint(c)# Counter({’a’: 3, ’l’: 2, ’g’: 1, ’h’: 1, ’d’: 1})c = Counter({’red’: 4, ’blue’: 2}) # a new counter from a mappingprint(c)# Counter({’red’: 4, ’blue’: 2})c = Counter(cats=4, dogs=8) # a new counter from keyword argsprint(c)# Counter({’dogs’: 8, ’cats’: 4})
除了基本的計數功能,它還支持一些常用的相關功能。比如:
按照頻率排序(most_common([n]))。其中n是可選輸入,表示返回前n個最頻繁的元素和他們的頻率。默認情況下返回所有的元素。 按照頻率輸出元素本身(elements())。它會返回元素本身,但是元素的順序不是原來的,相同的元素會連續輸出。不同元素之間,按照他們的出現順序輸出,這一點是OrderedDict以及3.7之后的dict所提供的特性。 兩個Counter相減(substract(c))。它可以從第一個counter上減去第二個counter中對應元素出現的次數。對于只出現在第二個coutner中元素,默認其在第一個counter中出現0次。c = Counter(a=4, b=2, c=0, d=-2)sorted(c.elements())# [’a’, ’a’, ’a’, ’a’, ’b’, ’b’]Counter(’abracadabra’).most_common(3)# [(’a’, 5), (’b’, 2), (’r’, 2)]c1 = Counter(a=4, b=2, d=-2)c2 = Counter(a=1, b=2, c=3, d=4)c1.subtract(c2)c1# Counter({’a’: 3, ’b’: 0, ’c’: -3, ’d’: -6})
更多的參考信息大家可以參考官方文檔:
https://docs.python.org/3/library/collections.html
以上就是4種非常實用的python內置數據結構的詳細內容,更多關于python內置數據結構的資料請關注好吧啦網其它相關文章!
相關文章: