Collections中的各种方法
一、各种方法介绍
Counter 统计个数 elements most_common subtract
defaultdict 字典默认值
ChainMap 合并多个映射对象(字典)
OrderdDict 有顺序的字典
deque 双向队列,可限制长度 append,appendleft,ratote
namedtuple 命名元祖
二、代码部分
from collections import Counter, defaultdict, ChainMap, OrderedDict, deque, namedtuple
"1.Counter"
# 三个方法,在前面的博客词频统计有学习过。
s = 'de8g love python so much'
counter = Counter(s)
# print(counter, type(counter))
# print(list(counter.elements()))
print(counter.most_common(5)) # 排序
counter.subtract('o') # 对某一个统计减少一次
print(counter.most_common(5)) # 排序
"2. 默认字典"
# 默认字典defaultdict 在lambda中学习过
defaultdict(lambda: 0)
defaultdict(lambda: 'abc')
c = defaultdict(lambda: (3,6))
c['a']
print(c)
# 默认字典在传统的统计里面使用
s = 'de8ug loves you so de8ug loves you so much you so much much '
# count_spilt = {}
dc_words = defaultdict(int) # 或者 lambda: 0
dc_words[10]
for i in s.split(' '):
# if i in count_spilt:
# count_spilt[i] += 1
# else:
# count_spilt[i] = 1
dc_words[i] += 1
print(dc_words)
# 默认字典的赋值为空列表
line = [(1,2),(1,3),(3,6),(4,7),(3,9),(4,9),(5,10)]
# 把相同x的y 追加到列表中
# line_new = {1:[2,3],3:{6,9}}
line_new = {}
for x,y in line:
if x not in line_new:
line_new[x] = [y]
else:
line_new[x].append(y)
print(line_new)
# -----------------------
line_dic = defaultdict(list) # 新做法
for x, y in line:
line_dic[x].append(y)
print(line_dic)
"3. ChainMap "
# 把两个字典组合起来
d1 = {'debug':1,"louhui":2,"diaosi":3}
d2 = {1: [2, 3], 3: [6, 9], 4: [7, 9], 5: [10]}
chain = ChainMap(d1,d2)
d3 = {'louhui':'shuai', 'caoyu':4, 1:"1"}
chain.update(d3)
print(chain)
"4. OrderDict"
# 在python3 字典就是有序的,但是我们不能依赖他,可能会变化
# 传统做法
dict2 = {'': 2,'a': 3,'de8ug': 2,'e': 8,'k': 9,'loves': 2,'much': 3,'so': 3,'you': 3}
keys = dict2.keys()
sorted(keys)
for k in keys:
print(k, dict2['e'])
# 使用OrderDict
dd = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}
order_dic = Orderdd = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}
#按key排序
kd = OrderedDict(sorted(dd.items(), key=lambda t: t[0]))
#按照value排序
vd = OrderedDict(sorted(dd.items(),key=lambda t:t[1]))
"5. deque"
# deque - double-end que.双向队列,支持线程安全
de = deque()
de.append(1)
de.append(2)
de.appendleft(3)
print(de)
de1 = deque([1,2,3,4,5,6,7], 7)
print(de1)
de1.rotate(3) # 旋转
print(de1)
# 另外一个作用,tail类型。输出文件的最后几行
def tail_file(filename, n):
with open(filename, 'r') as f:
return deque(f, n)
print(tail_file('/Users/lh/my_learn_python/01-python/123.txt', 2))
"6. nametuple"
# 就是给元祖每个变量定义一个名字
# 三种命名格式
Point = namedtuple('Point', 'm,n')
Point = namedtuple('Point', 'm n')
Point = namedtuple('Point', ['x', 'y'])
# Ponit=namedtuple('Point-LH','x,y')
p = Point(1,2)
print(p)
print(p.x)