Counter

基本使用

from collections import Counter

#计数
c2 = Counter('qqa23')
print(c2)#Counter({'q': 2, 'a': 1, '2': 1, '3': 1})

#可以转换为字典
print(dict(c2))#{'q': 2, 'a': 1, '2': 1, '3': 1}

c1 = Counter([1,2,3,7,8,1])
print(c1) # Counter({1: 2, 2: 1, 3: 1, 7: 1, 8: 1})

扩展——update方法与topn的问题解决

from collections import Counter


users = ["whw1","whw2","naruto1","naruto2","whw1","whw1","naruto2"]

user_counter1 = Counter(users)
print(user_counter1) # Counter({'whw1': 3, 'naruto2': 2, 'whw2': 1, 'naruto1': 1})

user_counter2 = Counter("wsaadw2wqea")
print(user_counter2) # Counter({'w': 3, 'a': 3, 's': 1, 'd': 1, '2': 1, 'q': 1, 'e': 1})

### update方法
user_counter1.update(user_counter2)
print(user_counter1)
"""
Counter({'whw1': 3, 'w': 3, 'a': 3, 'naruto2': 2, 'whw2': 1, 'naruto1': 1, 's': 1, 'd': 1, '2': 1, 'q': 1, 'e': 1})
"""

### topn的问题 —— most_common方法
top3 = user_counter1.most_common(3)
print(top3) # [('whw1', 3), ('w', 3), ('a', 3)]

namedtuple

简单说明

from collections import namedtuple

# 命名元组
# 作用:将元组中的元素进行明确标明,让别人知道这个元素是什么意思
#      明确的标明每个元素是什么意思

# t1 得到的是一个类
t1 = namedtuple('wanghw',['name','age','sex','hobby'])
print(t1)#<class '__main__.wanghw'>
## tt是t1实例化的对象
tt = t1('王宏伟','21','male','basketball')
print(tt)#wanghw(name='王宏伟', age='21', sex='male', hobby='basketball')

## 最后可以找tt的属性
print(tt.name)#王宏伟

实际需求

# -*- coding:utf-8 -*-
from collections import namedtuple


### 需求:user表的数据全部取出,然后新加一个列

# 创建一个类 —— 新加一个列:edu
User = namedtuple("User",["name","age","sex","hobby","edu"])

user_tuple = ("naruto",18,"male","螺旋丸")
user_lst = ["sasuke",18,"male","千鸟流"]

user_dict = {
    "name":"whw",
    "age":22,
    "sex":"male",
    "hobby":"pingpang",
    "edu":"master",

}

# 新加一个edu列
user = User(*user_tuple,edu="master")

# 1、取数 —— 注意这里的*other可以获取剩下所有的值
name,age,*other = user
print(name,age,other) # naruto 18 ['male', '螺旋丸', 'master']

# 2、_asdict()方法
user_info_dic = user._asdict()
print(user_info_dic) # OrderedDict([('name', 'naruto'), ('age', 18), ('sex', 'male'), ('hobby', '螺旋丸'), ('edu', 'master')])

deque

注意:deque是线程安全的,list不是线程安全的!

from collections import deque

#双端队列——支持列表的操作!
d = deque([1,2,3,4])
print(d)#deque([1, 2, 3, 4])
#右边添加
d.append(5)#deque([1, 2, 3, 4, 5])
print(d)
#左边添加
d.appendleft(6)
print(d)#deque([6, 1, 2, 3, 4, 5])
#pop——不能给参数
print(d.pop())#5
print(d.popleft())#6
print(d)#deque([1, 2, 3, 4])

OrderedDict

from collections import OrderedDict

user_dic = OrderedDict()

user_dic["a"] = "whw"
user_dic["b"] = "sasuke"
user_dic["c"] = "naruto"

### popitem方法 —— 默认pop最后一个键值对
"""
print(user_dic.popitem()) # ('c', 'naruto')
print(user_dic) # OrderedDict([('a', 'whw'), ('b', 'sasuke')])
"""
### popitem方法 —— 设置last为False的话pop第一个键值对
"""
print(user_dic.popitem(last=False)) # ('a', 'whw')
print(user_dic) # OrderedDict([('b', 'sasuke'), ('c', 'naruto')])
"""

### pop方法 —— 指定key
"""
print(user_dic.pop("b")) # sasuke
print(user_dic) # OrderedDict([('a', 'whw'), ('c', 'naruto')])
"""

### move_to_end方法 ———— 注意这个返回值为None!是在源字典中做的操作!
print(user_dic.move_to_end("b")) # None
print(user_dic) # OrderedDict([('a', 'whw'), ('c', 'naruto'), ('b', 'sasuke')])

ChainMap

from collections import ChainMap


# 两个字典有相同的key:b
user_dic1 = {"a":"whw1","b":"whw2"}
user_dic2 = {"b":"whw3","d":"whw4"}

### ChainMap
new_dic = ChainMap(user_dic1,user_dic2)

# maps
print(new_dic.maps)
"""
[{'a': 'whw1', 'b': 'whw2'}, {'b': 'whw3', 'd': 'whw4'}]
"""

# 遍历取值
for key,value in new_dic.items():
    print(f"{key}:{value}")
"""
### 注意,返回的结果是没有顺序的!!!
b:whw2
a:whw1
d:whw4 # 冲突的话使用第一个字典的key
"""

# 修改值
new_dic.maps[0]["a"] = "wanghongwei"
for key,value in new_dic.items():
    print(f"{key}:{value}")
"""
b:whw2
a:wanghongwei
d:whw4
"""

defaultdict

使用频率非常高。

Python中defaultdict的使用