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