Vanson's Eternal Blog

Python中的Collection集合类

Python collection.png
Published on
/7 mins read/---

Collection

提供了许多强大的集合类,这些类在处理数据时非常有用。通过使用这些集合类,你可以编写更简洁、更高效的代码。

namedtuple

创建具有命名字段的元组子类。

  • 不可变:namedtuple 的实例是不可变的,类似于普通元组。
  • 字段访问:可以通过字段名称访问元素,也可以通过索引访问元素。
 
from collections import namedtuple
 
# 定义一个 namedtuple 类型
Person = namedtuple('Person', ['name', 'age', 'gender'])
 
# 创建一个 namedtuple 实例
person = Person(name='Alice', age=30, gender='Female')
 
# 访问字段
print(person.name)  # 输出: Alice
print(person.age)   # 输出: 30
print(person.gender)  # 输出: Female
 

deque

双端队列,支持从两端高效地添加和删除元素。

  • 从两端添加和删除元素的时间复杂度为 O(1)。
  • 支持从两端操作,适用于队列和栈的实现。
from collections import deque
 
# 创建一个 deque
dq = deque([1, 2, 3])
 
# 在右侧添加元素
dq.append(4)
print(dq)  # 输出: deque([1, 2, 3, 4])
 
# 在左侧添加元素
dq.appendleft(0)
print(dq)  # 输出: deque([0, 1, 2, 3, 4])
 
# 从右侧移除元素
dq.pop()
print(dq)  # 输出: deque([0, 1, 2, 3])
 
# 从左侧移除元素
dq.popleft()
print(dq)  # 输出: deque([1, 2, 3])
 

Counter

用于计数的字典,可以快速统计元素的出现次数。

  • 基于字典实现,计数操作的时间复杂度为 O(1)。
  • 支持多种计数操作,如 most_common 和 update。
from collections import Counter
 
# 创建一个 Counter 对象
data = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
counter = Counter(data)
 
# 获取元素的计数
print(counter)  # 输出: Counter({4: 4, 3: 3, 2: 2, 1: 1})
 
# 获取最常见的元素
print(counter.most_common(1))  # 输出: [(4, 4)]
 
# 更新计数
counter.update([1, 1, 1])
print(counter)  # 输出: Counter({1: 4, 4: 4, 3: 3, 2: 2})

defaultdict

默认字典,当访问不存在的键时,会自动创建一个默认值。

  • 访问不存在的键时,会自动创建一个默认值。
  • 可以指定任意类型的默认值。
from collections import defaultdict
 
# 创建一个 defaultdict,指定默认值为 int(默认为 0)
dd = defaultdict(int)
 
# 访问不存在的键
print(dd['key'])  # 输出: 0
 
# 使用默认值
dd['key'] += 1
print(dd['key'])  # 输出: 1
 
# 使用其他默认值类型
dd_str = defaultdict(str)
print(dd_str['key'])  # 输出: ''
 

OrderedDict

有序字典,保持插入顺序。

  • 保持插入顺序。
  • 支持移动元素到末尾等操作。
 
from collections import OrderedDict
 
# 创建一个 OrderedDict
od = OrderedDict()
od['a'] = 1
od['b'] = 2
od['c'] = 3
 
# 遍历有序字典
for key, value in od.items():
    print(f"{key}: {value}")
# 输出:
# a: 1
# b: 2
# c: 3
 
# 移动元素到末尾
od.move_to_end('a')
print(od)  # 输出: OrderedDict([('b', 2), ('c', 3), ('a', 1)])
 

ChainMap

将多个字典逻辑上组合成一个字典。

  • 逻辑上组合多个字典。
  • 支持更新和访问组合后的字典。
from collections import ChainMap
 
# 创建两个字典
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
 
# 创建一个 ChainMap
chain_map = ChainMap(dict1, dict2)
 
# 访问元素
print(chain_map['a'])  # 输出: 1
print(chain_map['b'])  # 输出: 2
print(chain_map['c'])  # 输出: 4
 
# 更新元素
chain_map['a'] = 10
print(chain_map['a'])  # 输出: 10
print(dict1)  # 输出: {'a': 10, 'b': 2}

UserString

提供了一个可定制的字符串类,允许你创建自定义的字符串行为。

可以自定义字符串的行为,如添加和删除操作。

from collections import UserString
 
class MyString(UserString):
    def __init__(self, seq):
        super().__init__(seq)
 
    def append(self, s):
        self.data += s
 
    def remove(self, s):
        self.data = self.data.replace(s, '')
 
# 使用自定义字符串
my_str = MyString("Hello")
my_str.append(" World")
print(my_str)  # 输出: Hello World
 
my_str.remove(" World")
print(my_str)  # 输出: Hello

UserList

提供了一个可定制的列表类,允许你创建自定义的列表行为。可以自定义列表的行为,如添加和删除操作。

from collections import UserList
 
class MyList(UserList):
    def append(self, item):
        print(f"Appending {item}")
        super().append(item)
 
    def remove(self, item):
        print(f"Removing {item}")
        super().remove(item)
 
# 使用自定义列表
my_list = MyList([1, 2, 3])
my_list.append(4)  # 输出: Appending 4
print(my_list)  # 输出: [1, 2, 3, 4]
 
my_list.remove(4)  # 输出: Removing 4
print(my_list)  # 输出: [1, 2, 3]

Mapping 和 MutableMapping

提供了字典的抽象基类,允许你创建自定义的字典行为。可以自定义字典的行为,如添加、删除和迭代操作。

from collections.abc import MutableMapping
 
class MyDict(MutableMapping):
    def __init__(self, **kwargs):
        self._data = dict(**kwargs)
 
    def __getitem__(self, key):
        return self._data[key]
 
    def __setitem__(self, key, value):
        self._data[key] = value
 
    def __delitem__(self, key):
        del self._data[key]
 
    def __iter__(self):
        return iter(self._data)
 
    def __len__(self):
        return len(self._data)
 
# 使用自定义字典
my_dict = MyDict(a=1, b=2)
print(my_dict['a'])  # 输出: 1
my_dict['c'] = 3
print(my_dict)  # 输出: {'a': 1, 'b': 2, 'c': 3}
del my_dict['a']
print(my_dict)  # 输出: {'b': 2, 'c': 3}
 

Sequence 和 MutableSequence

提供了列表的抽象基类,允许你创建自定义的列表行为。可以自定义列表的行为,如添加、删除和迭代操作。

from collections.abc import MutableSequence
 
class MyList(MutableSequence):
    def __init__(self, initial=None):
        self._data = list(initial) if initial is not None else []
 
    def __getitem__(self, index):
        return self._data[index]
 
    def __setitem__(self, index, value):
        self._data[index] = value
 
    def __delitem__(self, index):
        del self._data[index]
 
    def __len__(self):
        return len(self._data)
 
    def insert(self, index, value):
        self._data.insert(index, value)
 
# 使用自定义列表
my_list = MyList([1, 2, 3])
print(my_list[0])  # 输出: 1
my_list.append(4)  # 输出: [1, 2, 3, 4]
del my_list[0]
print(my_list)  # 输出: [2, 3, 4]
 

Set 和 MutableSet

提供了集合的抽象基类,允许你创建自定义的集合行为。可以自定义集合的行为,如添加、删除和迭代操作。

from collections.abc import MutableSet
 
class MySet(MutableSet):
    def __init__(self, initial=None):
        self._data = set(initial) if initial is not None else set()
 
    def __contains__(self, item):
        return item in self._data
 
    def __iter__(self):
        return iter(self._data)
 
    def __len__(self):
        return len(self._data)
 
    def add(self, item):
        self._data.add(item)
 
    def discard(self, item):
        self._data.discard(item)
 
# 使用自定义集合
my_set = MySet([1, 2, 3])
print(1 in my_set)  # 输出: True
my_set.add(4)
print(my_set)  # 输出: {1, 2, 3, 4}
my_set.discard(1)
print(my_set)  # 输出: {2, 3, 4}