collections模块
python默认八大数据类型:整型、浮点型、字符串、字典、元组、列表、集合、布尔
collections模块:提供一些python八大数据类型以外的数据类型
-具名元组(只是一个名字,并不是元组)
应用场景:坐标
from collections import namedtuple
-有序字典
-python中字典默认是无序,collections提供了有序的字典
from collections import OrderedDict
#具名元组
#传入的可迭代对象是有序的
#应用:坐标
from collections import namedtuple
point1 = namedtuple('坐标',['x','y','z'])#第一个参数str,第二个参数传可迭代对象
point2 = namedtuple('坐标',('x','y','z'))
point3 = namedtuple('坐标','x y z')
#传参的个数要与namedtuple第二个参数的个数对应
p1 = point1(1,2,3)
p2 = point2(1,2,3)
p3 = point3(1,2,3)
print(p1)
print(p2)
print(p3)
print(type(p1))
>>>
坐标(x=1, y=2, z=3)
坐标(x=1, y=2, z=3)
坐标(x=1, y=2, z=3)
<class '__main__.坐标'>
#扑克牌
#获取扑克牌对象
card = namedtuple('扑克牌',['color','number'])
#由扑克牌对象产生一张牌
Heart_A = card('♥','A')
print(Heart_A)
Spade_K = card('♠','K')
print(Spade_K)
##有序字典
#python默认无序字典
dict1 = dict({'x':1,'y':2,'z':3})
print(dict1)
print(type(dict1))
for line in dict1:
print(line)
>>>
{'x': 1, 'y': 2, 'z': 3}
<class 'dict'>
x
y
z
from collections import OrderedDict
#有序字典
order_dict = OrderedDict({'x':1,'y':2,'z':3})
print(order_dict)
print(type(order_dict))
print(order_dict.get('x'))
print(order_dict['z'])
for line in order_dict:
print(line)
>>>
OrderedDict([('x', 1), ('y', 2), ('z', 3)])
<class 'collections.OrderedDict'>
1
3
x
y
z