目录
0. 学习资料
https://www.imooc.com/video/16361
1. collections
拥有的数据结构:
__all__ = ['deque', 'defaultdict', 'namedtuple', 'UserDict', 'UserList',
'UserString', 'Counter', 'OrderedDict', 'ChainMap']
1.1 tuple
-
不可变的(性能优化、线程安全、可以作为dict的key(需要对象可哈希)、拆包),可迭代对象
-
拆包:自动将位置对应值与变量进行映射
# 拆包:自动将位置对应值与变量进行映射 one, two, three = tuple_demo print(one, two, three) # 1 3 5 # 拆包: 只需要取前面第一个值的情况 on, *other = tuple_demo print(on) # 1
1.2 nametuple
#!/usr/bin/env/python3
# -*- coding:utf-8 -*-
"""
@project: collections_mkw
@author: zy7y
@file: nametuple_test.py
@ide: PyCharm
@time: 2020/8/28
"""
from collections import namedtuple
# 生成一个类, 第一个参数为一个类型名称,第二个参数列表是生成类的一个属性列表
User = namedtuple("user", ["name", "age", "height"])
user = User(name="zy7y", age=18, height=157)
print(user.name, user.age, user.height)
# 可变参数、元祖解包,函数传参方式之一
user_tuple = ("zy7y", 18)
# *user_tuple 表示解包操作,按顺序解包获得 zy7y 18 传递进去,
user_zy7y = User(*user_tuple, 157)
print(user_zy7y.name, user_zy7y.age, user_zy7y.height) # zy7y 18 157
# 字典解包, 函数传参方式之一
user_dict = {
"name": "kelan",
"age": 17,
"height": 158
}
user_dict_zy7y = User(**user_dict)
print(user_dict_zy7y.name, user_dict_zy7y.age, user_dict_zy7y.height) # kelan 17 158
# _make方法传参, 传入一个可迭代对象
user = User._make('str')
print(user.name, user.height, user.age) # s r t
# _asdict() 将类属性(nametuple)转换成orderdict
user_dict = user._asdict()
print(user_dict) # OrderedDict([('name', 's'), ('age', 't'), ('height', 'r')])
# nametuple拆包
name, age, height = user
print(name, age, height) # s t r
1.3 defaultdict
https://www.imooc.com/video/16364
# defaultdict 实现字典嵌套
def gen_defult():
return {
"name": "zy7y"
}
defaultdict = defaultdict(gen_defult)
print(defaultdict["name"])
count_user = ["a", "b", "c", "a", "b"]
# 统计上面每个值出现的次数
count_user_dict = {}
for user in count_user:
if user not in count_user_dict:
count_user_dict[user] = 1
else:
count_user_dict[user] += 1
print(count_user_dict) # {'a': 2, 'b': 2, 'c': 1}
from collections import defaultdict
# 使用defaultdict实现. 传递可调用对象intlist函数
dt = defaultdict(int)
for user in count_user:
dt[user] += 1
print(dt) # defaultdict(<class 'int'>, {'a': 2, 'b': 2, 'c': 1})
1.4 deque
# deque:双端队列
from collections import deque
# deque(可迭代对象)
user_list = deque(["zy", "7y"])
# 队列尾添加
user_list.append("kn")
# 队列前 添加
user_list.appendleft("tn")
print(user_list)
# extend: 合并两个deque 不返回新的deque
# insert(下标, 值): 指定下标位置,插入一个数据
1.5 Counter
# Counter 统计, 传入可迭代对象
user_list = Counter(user_list) # Counter({'tn': 1, 'zy': 1, '7y': 1, 'kn': 1})
# 合并后统计
user_list.update(["zy", "7y"]) # Counter({'tn': 1, 'zy': 1, '7y': 1, 'kn': 1})
print(user_list)
# 统计出前n个最多的内容
result = user_list.most_common(3) # [('zy', 2), ('7y', 2), ('tn', 1)]
print(result)
1.6 OrderDict
# OrderedDict: python3后 dict orderdDict都是有序的(先添加的在前面)
from collections import OrderedDict
user_dict = OrderedDict()
user_dict["key"] = 1
user_dict["kv"] = 2
# 移除最后一个 ,不需要传入key
print(user_dict.popitem())
print(user_dict) # {'key': 1}
user_dict["kv"] = 2
# 将元素移动到某个位置
user_dict.move_to_end("kv", False)
"""
'''Move an existing element to the end (or beginning if last is false). Raise KeyError if the element does not exist.
''将现有元素移动到末尾(如果last为false,则将其移动到开始)。如果元素不存在,则引发KeyError。
"""
print(user_dict)
1.7 ChainMap
# ChainMap
from collections import ChainMap
user_dict1 = {"a": 1, "b": 2}
user_dict2 = {"c": 3, "d": {"k": "v"}}
new_dict = ChainMap(user_dict1, user_dict2)
print(new_dict.maps, type(new_dict.maps)) # 转换成列表
# 动态添加new_dict.maps ,返回一个新的ChainMap
new_map = new_dict.new_child({"ss": 11})
for k, v in new_dict.items():
print(k, v)