python collections模塊的使用
collections模塊
collections模塊:提供一些python八大類型以外的數(shù)據(jù)類型
python默認(rèn)八大數(shù)據(jù)類型:
- 整型
- 浮點型
- 字符串
- 字典
- 列表
- 元組
- 集合
- 布爾類型
1、具名元組
具名元組只是一個名字
應(yīng)用場景:
① 坐標(biāo)
# 應(yīng)用:坐標(biāo)from collections import namedtuple# 將'坐標(biāo)'變成'對象'的名字# 傳入可迭代對象必須是有序的point = namedtuple('坐標(biāo)', ['x', 'y' ,'z']) # 第二個參數(shù)既可以傳可迭代對象# point = namedtuple('坐標(biāo)', 'x y z') # 也可以傳字符串,但是字符串之間以空格隔開p = point(1, 2, 5) # 注意元素的個數(shù)必須跟namedtuple中傳入的可迭代對象里面的值數(shù)量一致# 會將1 --> x , 2 --> y , 5 --> zprint(p)print(p.x)print(p.y)print(p.z)
執(zhí)行結(jié)果:
坐標(biāo)(x=1, y=2, z=5)125
② 撲克牌
# 撲克牌from collections import namedtuple# 獲取撲克牌對象card = namedtuple('撲克牌', 'color number')# 產(chǎn)生一張張撲克牌red_A = card('紅桃', 'A')print(red_A)black_K = card('黑桃', 'K')print(black_K)
執(zhí)行結(jié)果:
撲克牌(color=’紅桃’, number=’A’)撲克牌(color=’黑桃’, number=’K’)
③ 個人信息
# 個人的信息from collections import namedtuplep = namedtuple('china', 'city name age')ty = p('TB', 'ty', '31')print(ty)
執(zhí)行結(jié)果:
china(city=’TB’, name=’ty’, age=’31’)
2、有序字典
python中字典默認(rèn)是無序的
collections中提供了有序的字典: from collections import OrderedDict
# python默認(rèn)無序字典dict1 = dict({'x': 1, 'y': 2, 'z': 3})print(dict1, ' ------> 無序字典')print(dict1.get('x'))# 使用collections模塊打印有序字典from collections import OrderedDictorder_dict = OrderedDict({'x': 1, 'y': 2, 'z': 3})print(order_dict, ' ------> 有序字典')print(order_dict.get('x')) # 與字典取值一樣,使用.get()可以取值print(order_dict['x']) # 與字典取值一樣,使用key也可以取值print(order_dict.get('y'))print(order_dict['y'])print(order_dict.get('z'))print(order_dict['z'])
執(zhí)行結(jié)果:
{’x’: 1, ’y’: 2, ’z’: 3} ------> 無序字典1OrderedDict([(’x’, 1), (’y’, 2), (’z’, 3)]) ------> 有序字典112233
以上就是python collections模塊的使用的詳細(xì)內(nèi)容,更多關(guān)于python collections模塊的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. Python獲取抖音關(guān)注列表封號賬號的實現(xiàn)代碼2. ajax請求添加自定義header參數(shù)代碼3. Python數(shù)據(jù)分析之pandas函數(shù)詳解4. 解決Python 進(jìn)程池Pool中一些坑5. php測試程序運行速度和頁面執(zhí)行速度的代碼6. 無線標(biāo)記語言(WML)基礎(chǔ)之WMLScript 基礎(chǔ)第1/2頁7. 三個不常見的 HTML5 實用新特性簡介8. 使用.net core 自帶DI框架實現(xiàn)延遲加載功能9. php網(wǎng)絡(luò)安全中命令執(zhí)行漏洞的產(chǎn)生及本質(zhì)探究10. Warning: require(): open_basedir restriction in effect,目錄配置open_basedir報錯問題分析
