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‘]
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‘