亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

python collections模塊的使用

 更新時(shí)間:2020年10月16日 08:38:00   作者:Gg、  
這篇文章主要介紹了python collections模塊的使用,幫助大家更好的理解和使用python,感興趣的朋友可以了解下

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")  # 也可以傳字符串,但是字符串之間以空格隔開
p = point(1, 2, 5)  # 注意元素的個(gè)數(shù)必須跟namedtuple中傳入的可迭代對(duì)象里面的值數(shù)量一致

# 會(huì)將1 --> x , 2 --> y , 5 --> z
print(p)
print(p.x)
print(p.y)
print(p.z)

執(zhí)行結(jié)果:

坐標(biāo)(x=1, y=2, z=5)
1
2
5

 ?、?撲克牌

# 撲克牌
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 namedtuple

p = 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 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"])

  執(zhí)行結(jié)果:

{'x': 1, 'y': 2, 'z': 3}  ------>  無(wú)序字典
1
OrderedDict([('x', 1), ('y', 2), ('z', 3)])  ------>  有序字典
1
1
2
2
3
3

以上就是python collections模塊的使用的詳細(xì)內(nèi)容,更多關(guān)于python collections模塊的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論