python collections模塊的使用
collections模塊
collections模塊:提供一些python八大類型以外的數據類型
python默認八大數據類型:
- 整型
- 浮點型
- 字符串
- 字典
- 列表
- 元組
- 集合
- 布爾類型
1、具名元組
具名元組只是一個名字
應用場景:
① 坐標
# 應用:坐標from collections import namedtuple# 將'坐標'變成'對象'的名字# 傳入可迭代對象必須是有序的point = namedtuple('坐標', ['x', 'y' ,'z']) # 第二個參數既可以傳可迭代對象# point = namedtuple('坐標', 'x y z') # 也可以傳字符串,但是字符串之間以空格隔開p = point(1, 2, 5) # 注意元素的個數必須跟namedtuple中傳入的可迭代對象里面的值數量一致# 會將1 --> x , 2 --> y , 5 --> zprint(p)print(p.x)print(p.y)print(p.z)
執行結果:
坐標(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)
執行結果:
撲克牌(color=’紅桃’, number=’A’)撲克牌(color=’黑桃’, number=’K’)
③ 個人信息
# 個人的信息from collections import namedtuplep = namedtuple('china', 'city name age')ty = p('TB', 'ty', '31')print(ty)
執行結果:
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'])
執行結果:
{’x’: 1, ’y’: 2, ’z’: 3} ------> 無序字典1OrderedDict([(’x’, 1), (’y’, 2), (’z’, 3)]) ------> 有序字典112233
以上就是python collections模塊的使用的詳細內容,更多關于python collections模塊的資料請關注好吧啦網其它相關文章!
相關文章: