一、collections 模块--容器数据库类型
1、defaultdict:接受 default_factory作为变量。
(1)设置 int 作为 default_factory,使得dedaultdict在计数方面发挥作用。
from collections import defaultdict s="mississippi" d=defaultdict(int) for k in s: d[k]+=1 print(list(d.items())) """ [('m', 1), ('i', 4), ('s', 4), ('p', 2)] """
(2)使用 list 作为 default_factory , 将序列号作为键值加入字典。
from collections import defaultdict lst=[('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)] d=defaultdict(list) for k,v in lst: d[k].append(v) print(list(d.items())) """ [('yellow', [1, 3]), ('blue', [2, 4]), ('red', [1])] """
(3)使用 set 作为 default_factory,构建字典集合
from collections import defaultdict lst=[('red', 1), ('blue', 2), ('red', 3), ('blue', 4), ('red', 1), ('blue', 4)] d=defaultdict(set) for k,v in lst: d[k].add(v) print(list(d.items())) """ [('red', {1, 3}), ('blue', {2, 4})] """
2、Counter对象--提供快速和方便的计数。
(1): most_common(n):提供 n 个频率最高的元素和计数
from collections import Counter c=Counter() s="aba" for i in s: c[i]+=1 print(dict(c)) print(c.most_common(1)) """ {'a': 2, 'b': 1} [('a', 2)] """
from collections import Counter s="131312324556" r=Counter(s).most_common(2) print(r) """ [('1', 3), ('3', 3)] """
(2) elements()---返回一个迭代器,每个元素重复计数的个数,如果一个元素的计数小于1, elements()
就会忽略它。
from collections import Counter c = Counter(a=4, b=2, c=0, d=-2) for i in c.elements(): print(i,end=" ") """ a a a a b b """
二、itertools--为高效循环而创建的迭代器函数。
(1)accumulate(iterable[,func])--创建迭代器,返回累加或者其他函数(add-求和,mul--求积)结果。
from itertools import accumulate import operator data=[1,2,3,4,5] print(list(accumulate(data,operator.add))) """ [1, 3, 6, 10, 15] """
(2)chain--创建一个迭代器,它首先返回第一个可迭代对象中所有元素,接着返回下一个可迭代对象中所有元素,直到耗尽所有可迭代对象中的元素。
可将多个序列处理为单个序列。
from itertools import chain print(list(chain("abc","def"))) """ ['a', 'b', 'c', 'd', 'e', 'f'] """
from itertools import chain data=["abc","def"] print(list(chain.from_iterable(data))) """ ['a', 'b', 'c', 'd', 'e', 'f'] """
(3)combinations(iterable,r)---返回由输入 iterable 中元素组成长度为 r 的子序列。
from itertools import combinations print(list(combinations("1234",2))) """ [('1', '2'), ('1', '3'), ('1', '4'), ('2', '3'), ('2', '4'), ('3', '4')] """
from itertools import combinations_with_replacement print(list(combinations_with_replacement("123",2))) """ [('1', '1'), ('1', '2'), ('1', '3'), ('2', '2'), ('2', '3'), ('3', '3')] """
(4) permutations(iterable, r=None)--连续返回由 iterable 元素生成长度为 r 的排列。
from itertools import permutations data=[1,2,3] print(list(permutations(data))) """ [(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)] """