collections模块
collections模块
提供一些python八大数据类型以外的数据类型
具名元组(namedtuple)
应用场景:坐标、扑克牌、演员信息等等
定义:namedtuple(名字,有序的可迭代对象)
1、坐标
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__.坐标'>
2、扑克牌
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)
3、演员的信息
# 演员的信息
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