日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python defaultdict 简单了解

發布時間:2025/3/15 python 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python defaultdict 简单了解 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

首先看官方文檔doc

總結:

  • 使用一個factory函數作為defaultdict對象的參數

    In [1]: from collections import defaultdictIn [2]: d = defaultdict(list)
  • 當給d中不存在的鍵k賦值時,d會使用初始化時的factory函數初始化鍵k的對應的值

    In [3]: d['a'] Out[3]: []

    但是如果初始化時,不提供這樣的factory函數會報異常
    使用int初始化時,默認值為0

    In [4]: d = defaultdict(int) In [5]: d['s'] Out[5]: 0
  • 其他與普通dict使用方式相同

  • class collections.defaultdict([default_factory[, ...]]) Returns a new dictionary-like object. defaultdict is a subclass of the built-in dict class. It overrides one method and adds one writable instance variable. The remaining functionality is the same as for the dict class and is not documented here.The first argument provides the initial value for the default_factory attribute; it defaults to None. All remaining arguments are treated the same as if they were passed to the dict constructor, including keyword arguments.New in version 2.5.defaultdict objects support the following method in addition to the standard dict operations:__missing__(key) If the default_factory attribute is None, this raises a KeyError exception with the key as argument.If default_factory is not None, it is called without arguments to provide a default value for the given key, this value is inserted in the dictionary for the key, and returned.If calling default_factory raises an exception this exception is propagated unchanged.This method is called by the __getitem__() method of the dict class when the requested key is not found; whatever it returns or raises is then returned or raised by __getitem__().Note that __missing__() is not called for any operations besides __getitem__(). This means that get() will, like normal dictionaries, return None as a default rather than using default_factory.defaultdict objects support the following instance variable:default_factory This attribute is used by the __missing__() method; it is initialized from the first argument to the constructor, if present, or to None, if absent.8.3.3.1. defaultdict Examples Using list as the default_factory, it is easy to group a sequence of key-value pairs into a dictionary of lists:>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)] >>> d = defaultdict(list) >>> for k, v in s: ... d[k].append(v) ... >>> d.items() [('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])] When each key is encountered for the first time, it is not already in the mapping; so an entry is automatically created using the default_factory function which returns an empty list. The list.append() operation then attaches the value to the new list. When keys are encountered again, the look-up proceeds normally (returning the list for that key) and the list.append() operation adds another value to the list. This technique is simpler and faster than an equivalent technique using dict.setdefault():>>> d = {} >>> for k, v in s: ... d.setdefault(k, []).append(v) ... >>> d.items() [('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])] Setting the default_factory to int makes the defaultdict useful for counting (like a bag or multiset in other languages):>>> s = 'mississippi' >>> d = defaultdict(int) >>> for k in s: ... d[k] += 1 ... >>> d.items() [('i', 4), ('p', 2), ('s', 4), ('m', 1)] When a letter is first encountered, it is missing from the mapping, so the default_factory function calls int() to supply a default count of zero. The increment operation then builds up the count for each letter.The function int() which always returns zero is just a special case of constant functions. A faster and more flexible way to create constant functions is to use itertools.repeat() which can supply any constant value (not just zero):>>> def constant_factory(value): ... return itertools.repeat(value).next >>> d = defaultdict(constant_factory('<missing>')) >>> d.update(name='John', action='ran') >>> '%(name)s %(action)s to %(object)s' % d 'John ran to <missing>' Setting the default_factory to set makes the defaultdict useful for building a dictionary of sets:>>> s = [('red', 1), ('blue', 2), ('red', 3), ('blue', 4), ('red', 1), ('blue', 4)] >>> d = defaultdict(set) >>> for k, v in s: ... d[k].add(v) ... >>> d.items() [('blue', set([2, 4])), ('red', set([1, 3]))]

    總結

    以上是生活随笔為你收集整理的python defaultdict 简单了解的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。