Python collections.nametuple()


一、问题

通过名字访问元组。



二、解决方案

collections.nametuple :nametuple(名称+元组),命名元组,使元组除了使用索引访问还可以使用名称访问。

两个参数:第一个是类名,第二个是类的各个字段名。

from collections import namedtuple

Point = namedtuple('Point', ['x', 'y'])
p = Point(1, 2)
print(p)
Point(x=1, y=2)

_fields:类属性,返回一个包含所有字段名称的元组。

print(p._fields)
('x', 'y')

_make():通过一个可迭代对象来实例化这个类。作用跟 Point(1, 2) 相同。

Point = Point._make([3, 4])
print(Point)
Point(x=3, y=4)

_replace():更改属性的值。

p = Point(x=1, y=2)
print(p)

p = p._replace(x=3)
print(p)
Point(x=1, y=2)
Point(x=3, y=2)

_asdict():把命名元组以 collections.OrderedDict 的形式返回。

print(Point._asdict())
OrderedDict([('x', 3), ('y', 4)])


三、用途

1.将代码从下标操作中解脱出来。

通过下标去操作其中的元素, 当添加新的列代码可能就会出错。


普通元组:

def add(tuple):
    sum = 0
    for i in tuple:
        sum = tuple[0] + tuple[1]
    return sum

print(add((1, 2)))		# print(add([1, 2]))
3

命名元组:

from collections import namedtuple

Point = namedtuple('Point', ['x', 'y'])
def add(lst):
    sum = 0
    for i in lst:
        p = Point(*lst)
        sum = p.x + p.y
    return sum

print(add([1, 2]))
3

2.作为字典的替代。

字典的存储需要更多的内存空间。命名元组更高效。

from collections import namedtuple

Point = namedtuple('Point', ['x', 'y', 'z'])
p = Point(0, 0, 0)
print(p)

a = {'x': 1, 'y': 2}
p = p._replace(**a)
print(p)
Point(x=0, y=0, z=0)
Point(x=1, y=2, z=0)


posted @   做梦当财神  阅读(109)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
历史上的今天:
2017-12-03 MongoDB(课时14 正则运算)
2017-12-03 MongoDB(课时13 where条件过滤)
2017-12-03 MongoDB(课时12 字段判断)
2017-12-03 MongoDB(课时11 嵌套集合)
点击右上角即可分享
微信分享提示