1. 程式人生 > >python collections 數據結構模塊

python collections 數據結構模塊

err {} pycha default ack lis ask bsp span

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

python collections 數據結構模塊