python collections模块的使用
collections模块
collections模块:提供一些python八大类型以外的数据类型
python默认八大数据类型:
-整型
-浮点型
-字符串
-字典
-列表
-元组
-集合
-布尔类型
1、具名元组
具名元组只是一个名字
应用场景:
①坐标
#应用:坐标
fromcollectionsimportnamedtuple
#将"坐标"变成"对象"的名字
#传入可迭代对象必须是有序的
point=namedtuple("坐标",["x","y","z"])#第二个参数既可以传可迭代对象
#point=namedtuple("坐标","xyz")#也可以传字符串,但是字符串之间以空格隔开
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
②扑克牌
#扑克牌
fromcollectionsimportnamedtuple
#获取扑克牌对象
card=namedtuple("扑克牌","colornumber")
#产生一张张扑克牌
red_A=card("红桃","A")
print(red_A)
black_K=card("黑桃","K")
print(black_K)
执行结果:
扑克牌(color='红桃',number='A') 扑克牌(color='黑桃',number='K')
③个人信息
#个人的信息
fromcollectionsimportnamedtuple
p=namedtuple("china","citynameage")
ty=p("TB","ty","31")
print(ty)
执行结果:
china(city='TB',name='ty',age='31')
2、有序字典
python中字典默认是无序的
collections中提供了有序的字典:fromcollectionsimportOrderedDict
#python默认无序字典
dict1=dict({"x":1,"y":2,"z":3})
print(dict1,"------>无序字典")
print(dict1.get("x"))
#使用collections模块打印有序字典
fromcollectionsimportOrderedDict
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
以上就是pythoncollections模块的使用的详细内容,更多关于pythoncollections模块的资料请关注毛票票其它相关文章!