python collections模塊的使用
collections模塊
collections模塊:提供一些python八大類(lèi)型以外的數(shù)據(jù)類(lèi)型
python默認(rèn)八大數(shù)據(jù)類(lèi)型:
- 整型
- 浮點(diǎn)型
- 字符串
- 字典
- 列表
- 元組
- 集合
- 布爾類(lèi)型
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. Ajax常用封裝庫(kù)——Axios的使用2. jsp網(wǎng)頁(yè)實(shí)現(xiàn)貪吃蛇小游戲3. CSS Hack大全-教你如何區(qū)分出IE6-IE10、FireFox、Chrome、Opera4. jsp+servlet簡(jiǎn)單實(shí)現(xiàn)上傳文件功能(保存目錄改進(jìn))5. 微信小程序授權(quán)登錄的最新實(shí)現(xiàn)方案詳解(2023年)6. 使用Blazor框架實(shí)現(xiàn)在前端瀏覽器中導(dǎo)入和導(dǎo)出Excel7. Python中selenium庫(kù)的用法詳解8. Python 條件語(yǔ)句9. 使用Python第三方庫(kù)pygame寫(xiě)個(gè)貪吃蛇小游戲10. 在服務(wù)器端的XSLT過(guò)程中的編碼問(wèn)題
