python collections模塊的使用
collections模塊
collections模塊:提供一些python八大類型以外的數(shù)據(jù)類型
python默認八大數(shù)據(jù)類型:
- 整型
- 浮點型
- 字符串
- 字典
- 列表
- 元組
- 集合
- 布爾類型
1、具名元組
具名元組只是一個名字
應用場景:
① 坐標
# 應用:坐標from collections import namedtuple# 將'坐標'變成'對象'的名字# 傳入可迭代對象必須是有序的point = namedtuple('坐標', ['x', 'y' ,'z']) # 第二個參數(shù)既可以傳可迭代對象# point = namedtuple('坐標', '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í)行結果:
坐標(x=1, y=2, z=5)125
② 撲克牌
# 撲克牌from collections import namedtuple# 獲取撲克牌對象card = namedtuple('撲克牌', 'color number')# 產生一張張撲克牌red_A = card('紅桃', 'A')print(red_A)black_K = card('黑桃', 'K')print(black_K)
執(zhí)行結果:
撲克牌(color=’紅桃’, number=’A’)撲克牌(color=’黑桃’, number=’K’)
③ 個人信息
# 個人的信息from collections import namedtuplep = namedtuple('china', 'city name age')ty = p('TB', 'ty', '31')print(ty)
執(zhí)行結果:
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í)行結果:
{’x’: 1, ’y’: 2, ’z’: 3} ------> 無序字典1OrderedDict([(’x’, 1), (’y’, 2), (’z’, 3)]) ------> 有序字典112233
以上就是python collections模塊的使用的詳細內容,更多關于python collections模塊的資料請關注好吧啦網(wǎng)其它相關文章!
相關文章:
1. IntelliJ IDEA設置默認瀏覽器的方法2. idea設置提示不區(qū)分大小寫的方法3. HTTP協(xié)議常用的請求頭和響應頭響應詳解說明(學習)4. IntelliJ IDEA創(chuàng)建web項目的方法5. VMware中如何安裝Ubuntu6. ASP.NET MVC通過勾選checkbox更改select的內容7. .NET SkiaSharp 生成二維碼驗證碼及指定區(qū)域截取方法實現(xiàn)8. CentOS郵件服務器搭建系列—— POP / IMAP 服務器的構建( Dovecot )9. docker容器調用yum報錯的解決辦法10. django創(chuàng)建css文件夾的具體方法
