Python 2.x 中如何使用collections模块进行高级数据结构操作
Python 2.x 中如何使用collections模块进行高级数据结构操作
导语:在Python的标准库中,collections模块提供了一些高级数据结构,能够方便地进行各种操作。本文将介绍collections模块主要提供的几种数据结构,并给出相关的代码示例。
一、CounterCounter是一个简单而强大的计数器工具,可以用来统计可迭代对象中每个元素出现的次数。
示例代码:
from collections import Counter 1. 统计一个列表中每个元素的出现次数 lst = [1, 1, 2, 3, 4, 4, 4, 5, 6, 6, 7] counter = Counter(lst) print(counter) 1. 输出结果 1. Counter({4: 3, 1: 2, 6: 2, 2: 1, 3: 1, 5: 1, 7: 1}) 1. 统计一个字符串中每个字符的出现次数 s = "Hello, World!" counter = Counter(s) print(counter) 1. 输出结果 1. Counter({'l': 3, 'o': 2, 'H': 1, 'e': 1, ',': 1, ' ': 1, 'W': 1, 'r': 1, 'd': 1, '!': 1}) 1. 获取出现次数最多的前3个元素及其次数 print(counter.most_common(3)) 1. 输出结果 1. [('l', 3), ('o', 2), ('H', 1)]登录后复制
示例代码:
from collections import defaultdict 1. 声明一个defaultdict,键的默认值设为0 d = defaultdict(int) print(d[1]) 1. 输出结果 1. 0 1. 声明一个defaultdict,键的默认值设为[] d = defaultdict(list) print(d[1]) 1. 输出结果 1. [] 1. 声明一个defaultdict,键的默认值设为None d = defaultdict(lambda: None) print(d[1]) 1. 输出结果 1. None登录后复制
示例代码:
from collections import OrderedDict 1. 声明一个OrderedDict d = OrderedDict() 1. 添加键值对 d[1] = 'a' d[2] = 'b' d[3] = 'c' 1. 遍历字典 for k, v in d.items(): print(k, v) 1. 输出结果 1. 1 a 1. 2 b 1. 3 c登录后复制
示例代码:
from collections import deque 1. 创建一个双端队列 d = deque() 1. 添加元素 d.append(1) d.append(2) d.append(3) 1. 输出队列元素 print(d) 1. 输出结果 1. deque([1, 2, 3]) 1. 弹出元素 print(d.popleft()) print(d.pop()) 1. 输出结果 1. 1 1. 3登录后复制
以上就是Python 2.x 中如何使用collections模块进行高级数据结构操作的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!