欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > 能源 > Python的collections模块:数据结构的百宝箱

Python的collections模块:数据结构的百宝箱

2025/5/21 14:50:08 来源:https://blog.csdn.net/kymppcds/article/details/148099879  浏览:    关键词:Python的collections模块:数据结构的百宝箱

Python的collections模块:数据结构的百宝箱

图片

对话实录

小白:处理数据时,Python自带的数据结构不够用,有更强大的工具吗?

专家:那可不能错过collections模块,它提供了许多高效实用的数据结构,能大幅提升数据处理的效率与灵活性。

collections功能介绍

1. Counter:统计元素出现次数

Counter用于统计可迭代对象中元素出现的频次。比如统计文本中单词出现次数:

from collections import Counter
text = "apple banana apple cherry banana apple"
word_list = text.split()
#统计次数
word_counter = Counter(word_list)
print(word_counter)
#输出为:
Counter({'apple': 3, 'banana': 2, 'cherry': 1})text2 = "apple banana apple cherry banana apple"
word_list2 = text2.split()
#使用update函数添加另一个可迭代对象,继续统计次数
word_counter.update(word_list2)
print(word_counter)
#输出为
Counter({'apple': 6, 'banana': 4, 'cherry': 2})

2. defaultdict:带有默认值的字典

普通字典访问不存在的键会报错,defaultdict则会自动创建默认值。例如按类别统计物品数量:

from collections import defaultdict
category_items = defaultdict(int)
items = [('fruit', 'apple'), ('fruit', 'banana'), ('vegetable', 'carrot'), ('fruit', 'cherry')]
for category, item in items:category_items[category] += 1
print(category_items)
#输出为:
defaultdict(<class 'int'>, {'fruit': 3, 'vegetable': 1})

defaultdict(int)表示默认值为 0,最终输出defaultdict(<class 'int'>, {'fruit': 3,'vegetable': 1}),适用于需预先初始化值的字典场景。

3. OrderedDict:有序字典

普通字典在 Python 3.6 前无序,3.7 后虽保持插入顺序,但OrderedDict能更明确表示有序性,还有操作顺序的方法。如记录用户操作步骤:

from collections import OrderedDict
user_actions = OrderedDict()
user_actions['step1'] = 'login'
user_actions['step2'] = 'browse products'
user_actions['step3'] = 'add to cart'
user_actions['step4'] = 'checkout'
for step, action in user_actions.items():print(f"{step}: {action}")

输出严格按插入顺序展示,适用于历史记录、任务流程管理等需保持元素顺序的场景。

另外大家都知道集合有去重的功能,但是集合是无序的,去重后会导致原来的对象变得无序。此时可以通过OrderedDict保持原来的顺序。举例如下:

listA = ['orange', 'apple', 'pear', 'banana','orange']
listB = set(listA)
print(listB)
#打印结果 集合去重后元组顺序改变了
{'banana', 'pear', 'orange', 'apple'}

我们通过有序字典
collections.OrderedDict.fromkeys()功能,对列表去重并保持有序

from collections import OrderedDict
listC = list(OrderedDict.fromkeys(listA))
print(listC)
['orange', 'apple', 'pear', 'banana']

4.deque:双端队列

deque允许在队列两端高效添加和删除操作。模拟任务队列,可在队首添加紧急任务,队尾添加普通任务:

from collections import deque
task_queue = deque()task_queue.append('task1')
task_queue.append('task2')
task_queue.appendleft('urgent_task')while task_queue:task = task_queue.popleft()print(f"Processing task: {task}")

appendleft在队首添加,popleft从队首取出,在广度优先搜索、缓存管理等需双向操作的队列场景中性能更优。

5.namedtuple:具名元组

namedtuple为元组元素命名,让代码更易读。如表示学生信息:

from collections import namedtuple
Student = namedtuple('Student', ['name', 'age', 'grade'])student1 = Student('Alice', 20, 'A')
print(student1.name)
print(student1.age)
print(student1.grade)

通过属性名访问元素,数据存储和传递时很方便,适用于数据结构固定、元素含义明确的场景。

6.ChainMap:合并多个映射

ChainMap可组合多个字典或映射,形成单一视图,在处理多个配置文件等场景中有用。如合并默认和用户自定义配置字典:

from collections import ChainMap
default_config = {'color': 'blue', 'font':'sans-serif'}
user_config = {'color':'red'}combined_config = ChainMap(user_config, default_config)
print(combined_config['color'])
print(combined_config['font'])
#输出为:
red
sans-serif

访问键时先在user_config查找,不存在再在default_config查找,输出red和sans-serif 。

7.UserDict:自定义字典类

UserDict是创建自定义字典类的基类。创建不允许删除键的字典类:

from collections import UserDict
class NoDeleteDict(UserDict):def __delitem__(self, key):raise NotImplementedError("删除操作不被允许")ndd = NoDeleteDict({'key1': 'value1', 'key2': 'value2'})# 尝试删除键会引发错误
del ndd['key1']

继承UserDict并覆盖方法,可定制符合需求的字典类。

8.UserList:自定义列表类

类似UserDict,UserList用于创建自定义列表类。创建只能存储整数的列表类:

from collections import UserList
class IntList(UserList):def append(self, item):if not isinstance(item, int):raise ValueError("只能添加整数")super().append(item)
il = IntList()
il.append(1)
# 尝试添加非整数会引发错误
# il.append('not an integer')  

可对列表操作进行约束和扩展,满足特定业务逻辑。

小白:哇,collections模块这么强大!

专家:熟练掌握它,你在Python数据处理上会更得心应手,快去实践吧!

常用函数及数据结构速查表

函数 / 数据结构

用法

说明

Counter

Counter(iterable)

统计可迭代对象中元素出现次数

defaultdict

defaultdict(default_factory)

带有默认值的字典,default_factory为可调用对象

OrderedDict

OrderedDict()

有序字典,保持元素插入顺序

deque

deque([iterable], maxlen=None)

双端队列,可设置最大长度maxlen

namedtuple

namedtuple('typename', 'field_names')

具名元组,typename为类型名,field_names为字段名

ChainMap

ChainMap(*maps)

合并多个映射

UserDict

class MyDict(UserDict)

用于创建自定义字典类的基类

UserList

class MyList(UserList)

用于创建自定义列表类的基类

图片

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词