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 --> z print(p) print(p.x) print(p.y) print(p.z)
執行結果:
坐標(x=1, y=2, z=5)
1
2
5
② 撲克牌
# 撲克牌 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 namedtuple p = 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 OrderedDict order_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} ------> 無序字典
1
OrderedDict([('x', 1), ('y', 2), ('z', 3)]) ------> 有序字典
1
1
2
2
3
3
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/173138.html
標籤:Python
