个性化阅读
专注于IT技术分析

Python集合模块:collections用法示例

点击下载

本文概述

Python集合模块被定义为用于存储数据集合的容器, 例如列表, 字典, 集合和元组等。引入该模块是为了改善内置集合容器的功能。

Python集合模块在其2.4版本中首次引入。

集合模块有不同类型, 如下所示:

namedtuple()

python namedtuple()函数返回一个类似于元组的对象, 并为该元组中的每个位置命名。它用于消除记住普通元组中元组对象的每个字段的索引的问题。

例子

pranshu = ('Pranshu', 24, 'M')
print(pranshu)

输出

('Pranshu', 24, 'M')

OrderedDict()

Python OrderedDict()与字典对象相似, 在字典对象中, 键保持插入顺序。如果我们尝试再次插入密钥, 则该密钥的先前值将被覆盖。

例子

import collections
d1=collections.OrderedDict()
d1['A']=10
d1['C']=12
d1['B']=11
d1['D']=13

for k, v in d1.items():
    print (k, v)

输出

A 10
C 12
B 11
D 13

defaultdict()

Python defaultdict()被定义为类似字典的对象。它是内置dict类的子类。它提供了字典提供的所有方法, 但是将第一个参数作为默认数据类型。

例子

from collections import defaultdict  
number = defaultdict(int)  
number['one'] = 1  
number['two'] = 2  
print(number['three'])

输出

0

Counter()

Python Counter是字典对象的子类, 可帮助计算可哈希对象。

例子

from collections import Counter  
c = Counter()
list = [1, 2, 3, 4, 5, 7, 8, 5, 9, 6, 10]  
Counter(list)
Counter({1:5, 2:4})  
list = [1, 2, 4, 7, 5, 1, 6, 7, 6, 9, 1]  
c = Counter(list)  
print(c[1])

输出

3

deque()

Python deque()是一个双端队列, 它允许我们从两端添加和删除元素。

例子

from collections import deque
list = ["x", "y", "z"]
deq = deque(list)
print(deq)

输出

deque(['x', 'y', 'z'])
赞(0)
未经允许不得转载:srcmini » Python集合模块:collections用法示例

评论 抢沙发

评论前必须登录!