python collections模块的使用

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

python collections模块的使用

Gg、   2020-10-16 我要评论

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

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们