python collections模塊的使用
collections模塊
collections模塊:提供一些python八大類型以外的數(shù)據(jù)類型
python默認(rèn)八大數(shù)據(jù)類型:
- 整型
- 浮點(diǎn)型
- 字符串
- 字典
- 列表
- 元組
- 集合
- 布爾類型
1、具名元組
具名元組只是一個(gè)名字
應(yīng)用場(chǎng)景:
① 坐標(biāo)
# 應(yīng)用:坐標(biāo)from collections import namedtuple# 將'坐標(biāo)'變成'對(duì)象'的名字# 傳入可迭代對(duì)象必須是有序的point = namedtuple('坐標(biāo)', ['x', 'y' ,'z']) # 第二個(gè)參數(shù)既可以傳可迭代對(duì)象# point = namedtuple('坐標(biāo)', 'x y z') # 也可以傳字符串,但是字符串之間以空格隔開(kāi)p = point(1, 2, 5) # 注意元素的個(gè)數(shù)必須跟namedtuple中傳入的可迭代對(duì)象里面的值數(shù)量一致# 會(huì)將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# 獲取撲克牌對(duì)象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’)
③ 個(gè)人信息
# 個(gè)人的信息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)是無(wú)序的
collections中提供了有序的字典: from collections import OrderedDict
# python默認(rèn)無(wú)序字典dict1 = dict({'x': 1, 'y': 2, 'z': 3})print(dict1, ' ------> 無(wú)序字典')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} ------> 無(wú)序字典1OrderedDict([(’x’, 1), (’y’, 2), (’z’, 3)]) ------> 有序字典112233
以上就是python collections模塊的使用的詳細(xì)內(nèi)容,更多關(guān)于python collections模塊的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. 用Spring JMS使異步消息變得簡(jiǎn)單2. PHP驗(yàn)證碼工具-Securimage3. 關(guān)于IDEA 2020.3 多窗口視圖丟失的問(wèn)題4. js實(shí)現(xiàn)碰撞檢測(cè)5. 一文帶你徹底理解Java序列化和反序列化6. JS實(shí)現(xiàn)前端動(dòng)態(tài)分頁(yè)碼代碼實(shí)例7. PHP使用Swagger生成好看的API文檔8. ASP.NET MVC使用jQuery ui的progressbar實(shí)現(xiàn)進(jìn)度條9. 通過(guò)實(shí)例解析Python文件操作實(shí)現(xiàn)步驟10. Python 下載Bing壁紙的示例

網(wǎng)公網(wǎng)安備