刘心向学(43):namedtuple — 给元组起个名字

360影视 日韩动漫 2025-09-08 16:24 1

摘要:Python深色版本defget_user_info:return"Bob", 30, "Teacher"# 返回一个元组name, age, job = get_user_infoprint(f"{name} is {age} years old.") #

分享兴趣,传播快乐,

增长见闻,留下美好!

亲爱的您,这里是LearningYard新学苑。

今天小编为大家带来文章

“刘心向学(43):namedtuple — 给元组起个名字”

Share interest, spread happiness,

Increase knowledge, leave a beautiful!

Dear, this is LearningYard Academy.

Today, the editor brings you an article.

“Liu Xin Xiang Xue (43): namedtuple — Giving Tuples a Name”

Welcome to your visit.

Python深色版本defget_user_info:return"Bob", 30, "Teacher"# 返回一个元组name, age, job = get_user_infoprint(f"{name} is {age} years old.") # 必须记住顺序

但如果返回值顺序变了,或者你记错了索引,程序就会出错。

But if the return order changes, or you misremember the index, your program will break.

With namedtuple, you can write:

Python深色版本from collections import namedtupleUser = namedtuple('User', ['name', 'age', 'job'])user = User('Bob', 30, 'Teacher')print(f"{user.name} is {user.age} years old.") # 清晰、安全

字段名让数据“有身份”,代码瞬间变得可读又健壮。

Field names give data an "identity", instantly making your code more readable and robust.

namedtuple is a factory function in the collections module used to create named tuple classes.

它生成的类:

The generated class:

继承自 tuple,因此不可变、可哈希、可作为字典键Inherits from tuple, so it is immutable, hashable, and can be used as a dictionary key支持通过字段名访问元素(如 obj.name)Supports access by field name (e.g., obj.name)支持索引和切片(如 obj[0])Supports indexing and slicing (e.g., obj[0])内存占用小,性能高

Has low memory footprint and high performance

一句话:它是“带名字的元组”,是轻量级数据容器的理想选择。

Python深色版本from collections import namedtuple# 方法1:字段名用字符串(空格或逗号分隔)Point = namedtuple('Point', 'x y')# 方法2:字段名用列表Person = namedtuple('Person', ['name', 'age', 'job'])Python深色版本p = Point(3, 4)print(p.x, p.y) # 3 4print(p[0], p[1]) # 3 4print(len(p)) # 2# 拆包依然有效x, y = pPython深色版本# 从可迭代对象创建data = ['Alice', 28, 'Designer']person = Person._make(data)# 转为有序字典print(person._asdict)# OrderedDict([('name', 'Alice'), ('age', 28), ('job', 'Designer')])# 创建新实例(不可变)new_person = person._replace(age=29)print(new_person) # Person(name='Alice', age=29, job='Designer')# 查看字段名print(Person._fields) # ('name', 'age', 'job')Python深色版本Car = namedtuple('Car', ['brand', 'model', 'year'], defaults=[2020, 'Unknown'])car = Car('Tesla', 'Model 3')print(car) # Car(brand='Tesla', model='Model 3', year=2020)Python深色版本defget_stats(data):return namedtuple('Stats', 'mean median std')( mean=sum(data)/len(data), median=sorted(data)[len(data)//2], std=1.0# 简化 )result = get_stats([1,2,3,4,5])print(result.mean, result.std) # 3.0 1.0Python深色版本import csvfrom collections import namedtupleRow = namedtuple('Row', 'id,name,email')withopen('users.csv') as f: reader = csv.reader(f)for row inmap(Row._make, reader):print(f"Processing {row.name}")Python深色版本Config = namedtuple('Config', 'host port timeout')config = Config('localhost', 8080, 30)# 使用时清晰明确server.start(config.host, config.port)Python深色版本Color = namedtuple('Color', 'red green blue')RED = Color(255, 0, 0)GREEN = Color(0, 255, 0)print(RED.red) # 255六、与 typing.NamedTuple(推荐用于新项目)(With typing.NamedTuple (Recommended for New Projects))

Python 3.6+ 引入了 typing.NamedTuple,支持类型提示,更现代:

Python 3.6+ introduced typing.NamedTuple, which supports type hints and is more modern:

Python深色版本from typing import NamedTupleclassEmployee(NamedTuple): name: str age: int salary: float = 50000.0# 支持默认值emp = Employee("Charlie", 35)print(emp.salary) # 50000.0

建议:新项目优先使用 typing.NamedTuple,旧项目可用 collections.namedtuple。

Recommendation:Use typing.NamedTuple in new projects; use collections.namedtuple in legacy code.

Immutability和元组一样,namedtuple实例一旦创建就不能修改。需要修改时使用 _replace创建新实例。

Like tuples, namedtuple instances cannot be modified after creation. Use _replace to create a new instance when changes are needed.

不适合频繁修改的场景

如果数据需要频繁更新,考虑使用 dataclass 或普通类。

If data needs frequent updates, consider using dataclass or a regular class.

字段名不能是 Python 关键字或以 _ 开头

rename=True 自动重命名冲突字段。

If needed, set rename=True to automatically rename conflicting fields.

namedtuple 是 Python 标准库中一个“小而美”的工具。它用极低的性能开销,为元组带来了可读性、安全性与表达力

namedtuple

is a "small but beautiful" tool in Python’s standard library. With minimal performance overhead, it brings readability, safety, and expressiveness to tuples.

它不是要取代类或字典,而是填补了一个关键空白:当你需要一个不可变、轻量、命名清晰的数据结构时

It's not meant to replace classes or dictionaries, but fills a crucial gap:

Readability counts.
Simple is better than complex.

而 namedtuple,正是这一哲学的完美体现。

namedtuple

is a perfect embodiment of these principles.

下次当你写下 return x, y, z 时,不妨问自己:

“这三个值,有没有名字?”

Next time you write return x, y, z, ask yourself:

“Do these three values have names?”

如果有,那就用 namedtuple 给它们一个身份。

If they do, give them an identity with namedtuple.

今天的分享就到这里了。

如果您对文章有独特的想法,

欢迎给我们留言,

让我们相约明天。

祝您今天过得开心快乐!

That's all for today's sharing.

If you have a unique idea about the article,

please leave us a message,

and let us meet tomorrow.

I wish you a nice day!

参考资料:通义千问

参考文献:Beazley, D., & Jones, B. K. (2019). Python Cookbook (3rd ed.). O'Reilly Media.

Hettinger, R. (2019). Transforming Code into Beautiful, Idiomatic Python. PyCon US.

本文由LearningYard新学苑整理发出,如有侵权请在后台留言沟通!

LearningYard新学苑

文字:song

排版:song

审核|qiu

来源:LearningYard学苑

相关推荐