collections 数据结构模块namedtuple
namedtuple类
导入模块
from collections import namedtuple
使用方法及说明
#pycharm 里按住 ctrl键点击 collections可查看源码
#collections数据结构 #__all__ = ['deque', 'defaultdict', 'namedtuple', 'UserDict', 'UserList','UserString', 'Counter', 'OrderedDict', 'ChainMap']
使用说明:
#猜包功能
name = ("lijie",'ll') user = ("aa",23,189,'boddy') username,age,height,edu = user print (username,age,height,edu)
打印结果:
aa 23 189 boddy
#另一种方法 username,*other = user print (username,other)
打印结果:
aa [23, 189, 'boddy']
namedtuple
功能说明:
相当于创建一个类,并调用类的属性的值
#传统类的属性值调用 class User1(object): def __init__(self,name,age,height): self.name = name self.age = age self.height = height
常规操作
#使用namedtuple,namedtuple是tuple的子类,相比于class,节省空间,代码变少,使用方法如下:
User = namedtuple("user",['name','age','height']) #相当于类的初始化,初始化变量信息 user = User(name='test',age=23,height=111) #给各参数赋值 print (user.name,user.age,user.height) #直接打印类的属性的值
#增加一列(*args方式,元组)
User = namedtuple("user",['name','age','height',"edu"]) #假如edu为新增加的列 user = ('test',23,111) #元组 user_end = User(*user,"master") ##将数组传到namedtuple里,master为添加的edu的信息 print (user_end.name,user_end.age,user_end.height,user_end.edu)
#以**kwargs的方式增加列或传入数据(字典)
User = namedtuple("user",['name','age','height',"edu"]) user = { #字典 "name":'test', "age":23, "height":111 } user_end = User(**user,edu="master") ##将字典数据传到namedtuple里print (user_end.name,user_end.age,user_end.height,user_end.edu)
#_make方法 ##如果用_make方法,可以把“*”省略,但是要求tuple或者dict里的元素数量必须与nametuple里指定的属性数量相同,例: user1 = { "name":'test', "age":23, "height":111, "edu":"aa" } user_end = User._make(user1) print (user_end.name,....)
#当然,namedtuple也支持猜包
name,age,*other = user_end print (name,age,other)
额外补充
tuple 可作为字典的key,而list不可以,示例:
name_tuple = ("test",22,185,"baskerball") name_list = ["test1",22,188,"baseball"] dd = {} dd[name_tuple] = 'boddy' print (dd) dd[name_list] = 'body' print (dd)
打印结果:
{('test', 22, 185, 'baskerball'): 'boddy'}
Traceback (most recent call last):
File "D:/python-script/collections_module/chapter1/collection_module.py", line 29, in <module>
dd[name_list] = 'body'
TypeError: unhashable type: 'list'