# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: 'Python 3.8.2 32-bit (''_python_'': venv)'
#     name: python38232bitpythonvenv950369df46704df0a574ed247563cd7e
# ---

# - namedtuple
#     - 创建一个自定义的元组对象，并且规定了元组元素的个数
#     - 可以用属性而不是索引来引用元组的某个元素。
#     - 可以通过 namedtuple 来定义一种数据类型，它具备元组的不变性，又可以根据属性来引用

# +
from collections import namedtuple

Point = namedtuple('Point', ['x', 'y'])
p = Point(11, 22)

print(p.x)
print(p.y)
# -

# - deque
#     - 使用list 存储数据时，按照索引访问元素很快，插入和删除元素很慢，因为list是线性存储 数据量大的时候，插入和删除效率很低
#     - deque是为了高效实现插入和删除操作的双向列表，适合用于队列和栈。

# +
from collections import deque

data = deque(['a', 'b', 'c'])
data.append('x')
data.appendleft('y')

print(f"{data=}\n")

item = data.pop()
print(f"{item=}\n{data=}\n")

item = data.popleft()
print(f"{item=}\n{data=}")
# -

# > defaultdict
# >> 使用字典时，如果引用的Key不存在，就会抛出 KeyError，如果希望key不存在时，返回一个默认值，就可以用 defaultdict. 

# +
from collections import defaultdict

data = defaultdict(lambda: '-null-')
data['key1'] = 'value1'

print(f"{data['key1']=}")
print(f"{data['key2']=}")
# -

> OrderedDict
> 有序字典 OrderedDict 的有序性是按照插入的顺序，而不是Key的顺序。


# +
from collections import OrderedDict

data = dict([('b', 2), ('a', 1), ('c', 3)])
print(f"{data=}")

data = OrderedDict([('b', 2), ('a', 1), ('c', 3)])
print(f"{data=}")



# +
from collections import OrderedDict

# FIFO OrderedDict

class LimitOrderedDict(OrderedDict):

    def __init__(self, length):
        super().__init__()
        self.length = length

    def __setitem__(self, key, value):
        if key not in self:
            if len(self) == self.length:
                first = self.popitem(last=False)
                print(f"{first=}")
        super(LimitOrderedDict, self).__setitem__(key, value)


data = LimitOrderedDict(length=2)

data['key1'] = 'value1'
print(f"{data=}\n")

data['key2'] = 'value2'
print(f"{data=}\n")

data['key3'] = 'value3'
print(f"{data=}\n")
# -

# > Counter
# >> 简单的计数器

# +
from collections import Counter

c = Counter()
for i in 'abbcccdddd':
    c[i] = c[i] + 1

print(f"{c=}")

StarcoderdataJupyterScriptsDedupFiltered