Pythonのコレクションモジュールはデータ構造を強化します

collectionsは、Pythonの組み込みコレクションモジュールであり、多くの便利なコレクションクラスを提供します。多くの一般的な拡張データ構造クラスを含みます。データ構造が強化されている理由は、当然、一般的なタプルや辞書などが特定のニーズを満たしていない可能性があるためです。

カウンター

要素統計のリスト

通常の実現

>>> word_list = ["a", "b", "c", "c", "a", "a"]
>>> cnt = {}
>>> for word in set(word_list):
...     cnt[word] = word_list.count(word)
... 
>>> cnt
{'b': 1, 'c': 2, 'a': 3}
>>> cnt['d']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'd'

カウンターの実装 

>>> from collections import Counter
>>> cnt = Counter()
>>> word_list = ['a', 'b', 'c', 'c', 'a', 'a']
>>> for word in word_list:
...     cnt[word] += 1
... 
>>> cnt
Counter({'a': 3, 'c': 2, 'b': 1})
>>> cnt['a']
3
>>> cnt['d'] # 即使没有 key,也不会报 KeyError 哟,这点和 defaultdict(int) 比较像。
0

文字列文字統計

通常の実現

>>> word_str = 'hello world'
>>> word_list = list(word_str)
>>> cnt = {}
>>> for word in set(word_list):
...     cnt[word] = word_list.count(word)
... 
>>> cnt
{'e': 1, 'd': 1, 'h': 1, 'o': 2, 'l': 3, ' ': 1, 'r': 1, 'w': 1}

カウンターの実装

>>> from collections import Counter
>>> word_str = 'hello world'
>>> cnt = Counter(word_str)
>>> cnt
Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1})

>>> Counter({'red': 4, 'blue': 2})
Counter({'red': 4, 'blue': 2})
>>> Counter(red=4, blue=2)
Counter({'red': 4, 'blue': 2})

Counter.elements()

>>> cnt = Counter(red=4, blue=2)
>>> cnt
Counter({'red': 4, 'blue': 2})
>>> list(cnt.elements())
['red', 'red', 'red', 'red', 'blue', 'blue']

Counter.most_common()

>>> cnt = Counter('hello world')
>>> cnt
Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1})
>>> cnt.most_common()
[('l', 3), ('o', 2), ('h', 1), ('e', 1), (' ', 1), ('w', 1), ('r', 1), ('d', 1)]
>>> cnt.most_common(3)
[('l', 3), ('o', 2), ('h', 1)]

Counter.subtract()

>>> a = Counter(a=4, b=2, c=0, d=-2)
>>> a
Counter({'a': 4, 'b': 2, 'c': 0, 'd': -2})
>>> b = Counter(a=1, b=2, c=-3, d=4)
>>> b
Counter({'d': 4, 'b': 2, 'a': 1, 'c': -3})
>>> a.subtract(b)
>>> a
Counter({'a': 3, 'c': 3, 'b': 0, 'd': -6})

一般的な操作

実際、Counterタイプに変換した後の操作は、辞書の操作と同様です。

>>> from collections import Counter
>>> cnt = Counter('hello world')
>>> cnt
Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1})
>>> cnt.keys()
dict_keys(['h', 'e', 'l', 'o', ' ', 'w', 'r', 'd'])
>>> cnt.values()
dict_values([1, 1, 3, 2, 1, 1, 1, 1])
>>> sum(cnt.values())
11
>>> dict(cnt)
{'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}
>>> cnt.items()
dict_items([('h', 1), ('e', 1), ('l', 3), ('o', 2), (' ', 1), ('w', 1), ('r', 1), ('d', 1)])
>>> Counter(dict([('a', 1), ('b', 2), ('c', 3)]))
Counter({'c': 3, 'b': 2, 'a': 1})
>>> cnt.clear()
>>> cnt
Counter()

そして

Dequeは、スタックとキューの一般化された実装であり、一般に両端キューとして知られています。約O(1)のパフォーマンスで、両端キューの両端に要素を効率的に挿入および削除します。リストでも同様の操作がサポートされていますが、pop(0)およびinsert(0、v)(データの場所とサイズが変更されます)) O(n)時間計算量があります。これらの詳細を無視すると、彼を拡張リストとして扱うことに何の問題もないようです。

>>> from collections import deque
>>> 
>>> d = deque(['a', 'b', 'c'])
>>> d
deque(['a', 'b', 'c'])
>>> d.append('d')
>>> d
deque(['a', 'b', 'c', 'd'])
>>> d.count('b')
1
>>> d.extend(['e', 'f', 'g'])
>>> d
deque(['a', 'b', 'c', 'd', 'e', 'f', 'g'])
>>> d.pop()
'g'
>>> d
deque(['a', 'b', 'c', 'd', 'e', 'f'])
>>> d.remove('d')
>>> d
deque(['a', 'b', 'c', 'e', 'f'])
>>> d.reverse()
>>> d
deque(['f', 'e', 'c', 'b', 'a'])

# 队列左端操作
>>> d
deque(['f', 'e', 'c', 'b', 'a'])
>>> d.popleft()
'f'
>>> d
deque(['e', 'c', 'b', 'a'])
>>> d.appendleft('h')
>>> d
deque(['h', 'e', 'c', 'b', 'a'])
>>> d.extendleft(['i', 'j', 'k'])
>>> d
deque(['k', 'j', 'i', 'h', 'e', 'c', 'b', 'a'])
# 想想挖掘机的履带,rotate 就不难理解了
>>> d.rotate(1)
>>> d
deque(['a', 'k', 'j', 'i', 'h', 'e', 'c', 'b'])
>>> d.rotate(2)
>>> d
deque(['c', 'b', 'a', 'k', 'j', 'i', 'h', 'e'])

defaultdict

私にとってdefaultdictの最大の特徴は、KeyErrorエラーが発生しないことです。リスト要素の統計セクションに戻って確認できます。

要素統計のリスト

通常の実現

>>> word_list = ["a", "b", "c", "c", "a", "a"]
>>> cnt = {}
>>> for word in word_list:
...     if word not in cnt:
...             cnt[word] = 1
...     else:
...             cnt[word] += 1
... 
>>> cnt
{'a': 3, 'b': 1, 'c': 2}

>>> cnt['d']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'd'

Defaultdictの実装(elseステートメントを使用して判断する場合はありません)

>>> from collections import defaultdict
>>> word_list = ["a", "b", "c", "c", "a", "a"]
>>> cnt = defaultdict(int)
>>> for word in word_list:
...     cnt[word] += 1
... 
>>> cnt
defaultdict(<class 'int'>, {'a': 3, 'b': 1, 'c': 2})

OrderedDict

見ること、聞くこと、知ることは順序付けられた辞書であり、特に簡単に説明できるものはないようです。

>>> from collections import OrderedDict
>>> d = {"banana":3,"apple":2,"pear":1,"orange":4}
>>> order_dict = OrderedDict(d)
>>> order_dict
OrderedDict([('banana', 3), ('apple', 2), ('pear', 1), ('orange', 4)])
>>> order_dict.keys()
odict_keys(['banana', 'apple', 'pear', 'orange'])
>>> order_dict.values()
odict_values([3, 2, 1, 4])
>>> order_dict.items()
odict_items([('banana', 3), ('apple', 2), ('pear', 1), ('orange', 4)])

# 从后(前)删除元素
>>> order_dict.popitem(last=True)
('orange', 4)
>>> order_dict
OrderedDict([('banana', 3), ('apple', 2), ('pear', 1)])
>>> order_dict.popitem(last=False)
('banana', 3)
>>> order_dict
OrderedDict([('apple', 2), ('pear', 1)])

# 移动元素到末尾
>>> order_dict
OrderedDict([('apple', 2), ('pear', 1), ('orange', 4)])
>>> order_dict.move_to_end('apple')
>>> order_dict
OrderedDict([('pear', 1), ('orange', 4), ('apple', 2)])

 

おすすめ

転載: blog.csdn.net/TomorrowAndTuture/article/details/113850006