Python其他資料結構collection模組-namtuple defaultdict deque Queue Counter OrderDict

來源:互聯網
上載者:User

標籤:get   tde   named   元組   形式   基礎資料型別 (Elementary Data Type)   本質   default   numbers   

nametuple

  是tuple擴充子類,命名元組,其實本質上簡單類對象

from collections import namedtupleinfo = namedtuple("Info", [‘name‘, ‘age‘, ‘height‘])# 賦值,是不是有點像物件導向中執行個體變數方式info.name = "北門吹雪"info.age = 18info.height = 175# 訪問print(info.name)

  其實本質上和下面方式一樣

class Info:    def __init__(self):        self.name = None        self.age = None        self.height = None        passinfo = Info()# 賦值info.name = "北門吹雪"info.age = 18info.height = 175# 訪問print(info.name)

  相關方法

    1. _make 初始化賦值, 必須長度一致

from collections import namedtupleinfo = namedtuple("Info", [‘name‘, ‘age‘, ‘height‘])._make(["北門吹雪", 18, 175])# 訪問print(info.name)

    2. _asdict  將nametuple對象轉換為字典對象,是個有序字典

from collections import namedtupleinfo = namedtuple("Info", [‘name‘, ‘age‘, ‘height‘])._make(["北門吹雪", 18, 175])# 訪問print(info._asdict())

  

  

defaultdict

  是dict的擴充類,訪問字典的key如果沒有則自動化佈建預設值,並添加進字典

info = dict()name = info.setdefault(‘name‘, "北門吹雪")print(name, info)from collections import defaultdict# 預設值必須是可迭代對象info = defaultdict(lambda: "北門吹雪")name = info[‘name‘]print(name, info)

  

deque  

  雙端隊列, 操作和list類似

  list deque 推薦用來儲存相同類似資料,相關方法和list一致

  特性: deque是安全執行緒的,list不是安全執行緒,多線程編程則使用deque

from collections import dequenames = deque()names.append("北門吹雪")names.append("QiNiuYun")names.insert(0, "今日頭條")print(names)

  

Queue    

  隊列(先進先出),通過 deque實現

  核心兩個方法 put get,會堵塞

from queue import Queuemessage = Queue()# 放入資料message.put("北門吹雪")# 消費資料print(message.get())

  

Counter  

  對可迭代對象做統計出現個數,直接返回統計結果,是dict的子類

from collections import Counterfrom random import randintnumbers = [randint(1, 5) for _ in range(20)]numbers_count = Counter(numbers)print(numbers_count)

  相關方法

    1. update        添加新的資料

from collections import Counterfrom random import randintnumbers = [randint(1, 5) for _ in range(20)]numbers_count = Counter(numbers)print(numbers_count)# 添加新的資料numbers_count.update([randint(1, 10) for _ in range(20)])print(numbers_count)

    2. most_common(N)   輸出出現次數當前最多的前N個元素

from collections import Counterfrom random import randintnumbers = [randint(1, 5) for _ in range(20)]numbers_count = Counter(numbers)print(numbers_count)# 添加新的資料numbers_count.update([randint(1, 10) for _ in range(20)])print(numbers_count)# 輸出出現次數當前最多的前3個元素,返回列表print(numbers_count.most_common(3))

  

OrderDict

  繼承dict, 保持字典添加順序,具有dict所有方法

from collections import OrderedDictinfo = OrderedDict()# 填入資料info["name"] = "北門吹雪"info[‘age‘] = 18info[‘height‘] = 175print(info)

  其他方法

    1. popitem    預設刪除最後的key:value,並返回

from collections import OrderedDictinfo = OrderedDict()# 填入資料info["name"] = "北門吹雪"info[‘age‘] = 18info[‘height‘] = 175# 返回元組形式print(info.popitem(‘name‘))

    2. pop      必須傳入key,刪除key:value,返回value

from collections import OrderedDictinfo = OrderedDict()# 填入資料info["name"] = "北門吹雪"info[‘age‘] = 18info[‘height‘] = 175# 返回age對應的值print(info.pop(‘age‘))

    3. move_to_end   傳入key,將元素移到最後

from collections import OrderedDictinfo = OrderedDict()# 填入資料info["name"] = "北門吹雪"info[‘age‘] = 18info[‘height‘] = 175# 移動資料info.move_to_end(‘age‘)print(info)

  

經驗:

  1. 這些資料類型基礎還是從list tuple set dict基礎資料型別 (Elementary Data Type)擴充而來,本質上添加了一些特性

Python其他資料結構collection模組-namtuple defaultdict deque Queue Counter OrderDict

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.