collections模塊

collections模塊

提供一些python八大數據類型之外的數據類型python

具名元組(namedtuple)

應用場景:座標、撲克牌、演員信息等等app

定義:namedtuple(名字,有序的可迭代對象)dom

一、座標大數據

from collections import namedtuple
res = namedtuple('座標', ['x','y','z'])
# 傳入的參數與可迭代對象中元素一一對應
name_res = res(80,50,45) # (x=80, y=50, z=45)
print(name_res) #座標(x=80, y=50, z=45)
print(type(name_res)) # <class '__main__.座標'>

二、撲克牌code

from collections import namedtuple
card = namedtuple('撲克牌', ['花色', '點數'])
rea = card('♥','A')
print(rea)
# 將全部撲克牌放入一個列表中,而後打亂順序,而後再倒序發牌,從列表中抽出17張牌,分別給3個用戶,實現鬥地主發牌功能
from collections import namedtuple
import random
def get_card():
    card = namedtuple('撲克牌', ['花色', '點數'])
    l = ['A', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K']
    n = ['♥', '♠', '♦', '♣']
    card_list = []
    for s in n:
        for i in l:
            rea_ht = card(s, i)
            card_list.append(rea_ht)
    return card_list
card_list = get_card()
# print(card_list)
random.shuffle(card_list)
print(card_list)
user1 = []
for i in range(-1, -18, -1):
    res1 = card_list[i]
    user1.append(res1)
print(user1)
user2 = []
for i in range(-18, -35, -1):
    res2 = card_list[i]
    user2.append(res2)
print(user2)
user3 = []
for i in range(-35, -52, -1):
    res3 = card_list[i]
    user3.append(res3)
print(user3)

三、演員的信息對象

# 演員的信息
from collections import namedtuple
star = namedtuple('演員', 'name city sex')
star_name = star('古天樂', '香港', '男')
print(star_name) # 演員(name='古天樂', city='香港', sex='男')

有序字典(OrderdeDict)

# 有序字典
from collections import OrderedDict
dic = {'x': 1, 'y': 2, 'z': 3}
dic_order = OrderedDict(dic)
print(dic_order) # OrderedDict([('x', 1), ('y', 2), ('z', 3)])
print(type(dic_order)) # <class 'collections.OrderedDict'>
print(dic_order.get('x')) # 1
print(dic_order['y']) # 2

for i in dic_order:
    print(i) # x , y , z
相關文章
相關標籤/搜索