欢迎访问我的网站,希望内容对您有用,感兴趣的可以加入免费知识星球。

Python 中的 namedtuple

Python基础 迷途小书童 2年前 (2022-05-07) 943次浏览 0个评论

环境

  • python 3.8

前言

namedtuplecollections 模块中的一个容器类型。看名字,也带了 tuple,我们都知道 tuple 中的元素是不可以修改的,在映射中可以当键使用,而 namedtuple 不仅可以通过索引来访问,还可以通过属性名称来访问,同时还支持属性值的修改。

实例

下面在 ipython 中进行演示

(pytorch1.7) PS D:\Gogs> ipython
Python 3.8.11 (default, Aug  6 2021, 09:57:55) [MSC v.1916 64 bit (AMD64)]
Type 'copyright', 'credits' or 'license' for more information
IPython 7.26.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: from collections import namedtuple

# 定义一个namedtuple类型的Worker,列表中是它的属性
In [2]: Worker = namedtuple('Worker', ['name', 'sex', 'id', 'salary'])

# 实例化对象
In [3]: w1 = Worker('alex', 'male', '001', '10000')

# 通过索引获取值
In [4]: w1[0]
Out[4]: 'alex'

# 通过名称获取值
In [5]: w1.salary
Out[5]: '10000'

In [6]: w1.name
Out[6]: 'alex' 

# 通过_make方法来实例化,参数是一个list
In [7]: w2 = Worker._make(['lily', 'female', '002', '11000'])

In [8]: w2.name
Out[8]: 'lily'

In [9]: w2.salary
Out[9]: '11000'

# 修改对象的属性
In [10]: w2._replace(salary='15000')
Out[10]: Worker(name='lily', sex='female', id='002', salary='15000')

In [11]: w1
Out[11]: Worker(name='alex', sex='male', id='001', salary='10000')

# 通过方法_asdict,可以转换成字典
In [12]: w1._asdict()
Out[12]: {'name': 'alex', 'sex': 'male', 'id': '001', 'salary': '10000'}
喜欢 (0)

您必须 登录 才能发表评论!