python collections模塊的使用
collections模塊
collections模塊:提供一些python八大類型以外的數(shù)據(jù)類型
python默認八大數(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中字典默認是無序的
collections中提供了有序的字典: from collections import OrderedDict
# python默認無序字典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模塊的使用的詳細內(nèi)容,更多關(guān)于python collections模塊的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. 通過CSS數(shù)學(xué)函數(shù)實現(xiàn)動畫特效2. CSS3中Transition屬性詳解以及示例分享3. 阿里前端開發(fā)中的規(guī)范要求4. 低版本IE正常運行HTML5+CSS3網(wǎng)站的3種解決方案5. 利用CSS3新特性創(chuàng)建透明邊框三角6. XML入門的常見問題(二)7. CSS3實例分享之多重背景的實現(xiàn)(Multiple backgrounds)8. IE6/IE7/IE8/IE9中tbody的innerHTML不能賦值的完美解決方案9. XML入門的常見問題(一)10. 解析原生JS getComputedStyle
