Python高级编程-collections模块(番外篇)
x.1 collections模块介绍
from collections import *
from collections.abc import *
"""
提供了更加高级的数据结构
"""
x.2 tuple的功能
不可变,iterable
拆包 # name, *others = ("coder", 20, 175)
tuple不可变性不是绝对的 # ("name", [20, 175])
tuple比list好的地方
immutable的重要性:
性能优化:指出元素全部为immutable的tuple会作为常量在编译时确定,因此产生了如此显著的速度差异
线程安全
可以作为dict的key
拆包特性
如果要拿C语言来类比,Tuple对应的是struct,而List对应的是array
x.3 nametuple 详解
from collections import nametuple
User = nametuple("User", ["name", "age", "height"])
user = User(name="booby", age=29, height=175)
print(user.age, user.name, user.height)
"""
为什么不用类封装,而用nametuple?
因为使用nametuple会比class少去很多默认属性,更加节约空间。
"""
user_tuple = ("bobby", 29, 175)
user = User(*user_tuple) # User._make(user_tuple)
print(user._asdict())
name, age, height = user
x.4 defaultdict 功能详解
from collections import defaultdict
# 统计数量
user_dict