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 --> z
print(p)
print(p.x)
print(p.y)
print(p.z)
执行结果:
坐标(x=1, y=2, z=5)
1
2
5
② 扑克牌
# 扑克牌
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 namedtuple
p = 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 OrderedDict
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
以上就是python collections模块的使用的详细内容,更多关于python collections模块的资料请关注软件开发网其它相关文章!
您可能感兴趣的文章:Python collections模块的使用方法了解一下python内建模块collectionsPython collections.defaultdict模块用法详解简介Python的collections模块中defaultdict类型的用法Python的collections模块中的OrderedDict有序字典Python的collections模块中namedtuple结构使用示例详解Python的collections模块中的deque双端队列结构简单掌握Python的Collections模块中counter结构的用法Python中Collections模块的Counter容器类使用教程Python collections模块实例讲解