python namedtuple用法_详解Python中namedtuple的使用
namedtuple是Python中存储数据类型,比较常见的数据类型还有有list和tuple数据类型。相比于list,tuple中的元素不可修改,在映射中可以当键使用。
namedtuple:
namedtuple类位于collections模块,有了namedtuple后通过属性访问数据能够让我们的代码更加的直观更好维护。
namedtuple能够用来创建类似于元祖的数据类型,除了能够用索引来访问数据,能够迭代,还能够方便的通过属性名来访问数据。
接下来通过本文给大家分享python namedtuple()的使用,一起看看吧!
基本定义
collections.namedtuple(typename, field_names, *, rename=False, defaults=None, module=None)
(1)返回一个名为typename的新元组子类
(2)新的子类用于创建类似元组的对象,这些对象具有可通过属性查找访问的字段以及可索引和可迭代的字段field_names
typename
(1)typename表示这个子类的名字,比如C++、python、Java中的类名
field_names
(1)field_names是一个字符串序列,例如["x","y"]
(2)field_names可以是单个字符串,每个字段名都用空格或逗号分隔,例如"x y"或"x,y"
others
(1)其它的参数并不常用,这里不再介绍啦
基本样例
from collections import namedtuple
# 基本例子
Point = namedtuple("Point",["x","y"]) # 类名为Point,属性有"x"和"y"
p = Point(11, y=22) # 用位置或关键字参数实例化,因为"x"在"y"前,所以x=11,和函数参数赋值一样的
print(p[0]+p[1]) # 我们也可以使用下标来访问
# 33
x, y = p # 也可以像一个元组那样解析
print(x,y)
# (11, 22)
print(p.x+p.y) # 也可以通过属性名来访问
# 33
print(p) # 通过内置的__repr__函数,显示该对象的信息
# Point(x=11, y=22)
classmethodsomenamedtuple._make(iterable)
(1)从一个序列或者可迭代对象中直接对field_names中的属性直接赋值,返回一个对象
t = [11, 22] # 列表 list
p = Point._make(t) # 从列表中直接赋值,返回对象
print(Point(x=11, y=22))
# Point(x=11, y=22)
classmethodsomenamedtuple._asdict()
(1)之前也说过了,说它是元组,感觉更像一个带名字的字典
(2)我们也可以直接使用_asdict()将它解析为一个字典dict
p = Point(x=11, y=22) # 新建一个对象
d = p._asdict() # 解析并返回一个字典对象
print(d)
# {"x": 11, "y": 22}
classmethodsomenamedtuple._replace(**kwargs)
(1)这是对某些属性的值,进行修改的,从replace这个单词就可以看出来
(2)注意该函数返回的是一个新的对象,而不是对原始对象进行修改
p = Point(x=11, y=22) # x=11,y=22
print(p)
# Point(x=11, y=22)
d = p._replace(x=33) # x=33,y=22 新的对象
print(p)
# Point(x=11, y=22)
print(d)
# Point(x=33, y=22)
classmethodsomenamedtuple._fields
(1)该方法返回该对象的所有属性名,以元组的形式
(2)因为是元组,因此支持加法操作
print(p._fields) # 查看属性名
# ("x", "y")
Color = namedtuple("Color", "red green blue")
Pixel = namedtuple("Pixel", Point._fields + Color._fields) # 新建一个子类,使用多个属性名
q = Pixel(11, 22, 128, 255, 0)
print(q)
classmethodsomenamedtuple._field_defaults
(1)该方法是python3.8新增的函数,因为我的版本是3.6,无法验证其正确性
(2)下面给出官方的示例
Account = namedtuple("Account", ["type", "balance"], defaults=[0])
print(Account._field_defaults)
#{"balance": 0}
print(Account("premium"))
#Account(type="premium", balance=0)
getattr()函数
(1)用来获得属性的值
print(getattr(p, "x"))
# 11
字典创建namedtuple()
(1)从字典来构建namedtuple的对象
d = {"x": 11, "y": 22} # 字典
p = Point(**d) # 双星号是重点
print(p)
# Point(x=11, y=22)
CSV OR Sqlite3
(1)同样可以将从csv文件或者数据库中读取的文件存储到namedtuple中
(2)这里每次存的都是一行的内容
EmployeeRecord = namedtuple("EmployeeRecord", "name, age, title, department, paygrade")
import csv
for emp in map(EmployeeRecord._make, csv.reader(open("employees.csv", "r"))):
# 这里每行返回一个对象 注意!
print(emp.name, emp.title)
import sqlite3
conn = sqlite3.connect("/companydata") # 连接数据库
cursor = conn.cursor()
cursor.execute("SELECT name, age, title, department, paygrade FROM employees")
for emp in map(EmployeeRecord._make, cursor.fetchall()):
# 每行返回一个对象 注意!
print(emp.name, emp.title)
类的继承
(1)接下来用deepmind的开源项目graph_nets中的一段代码来介绍
NODES = "nodes"
EDGES = "edges"
RECEIVERS = "receivers"
SENDERS = "senders"
GLOBALS = "globals"
N_NODE = "n_node"
N_EDGE = "n_edge"
GRAPH_DATA_FIELDS = (NODES, EDGES, RECEIVERS, SENDERS, GLOBALS)
GRAPH_NUMBER_FIELDS = (N_NODE, N_EDGE)
class GraphsTuple(
# 定义元组子类名 以及字典形式的键名(属性名)
collections.namedtuple("GraphsTuple",
GRAPH_DATA_FIELDS + GRAPH_NUMBER_FIELDS)):
# 这个函数用来判断依赖是否满足,和我们的namedtuple关系不大
def _validate_none_fields(self):
"""Asserts that the set of `None` fields in the instance is valid."""
if self.n_node is None:
raise ValueError("Field `n_node` cannot be None")
if self.n_edge is None:
raise ValueError("Field `n_edge` cannot be None")
if self.receivers is None and self.senders is not None:
raise ValueError(
"Field `senders` must be None as field `receivers` is None")
if self.senders is None and self.receivers is not None:
raise ValueError(
"Field `receivers` must be None as field `senders` is None")
if self.receivers is None and self.edges is not None:
raise ValueError(
"Field `edges` must be None as field `receivers` and `senders` are "
"None")
# 用来初始化一些参数 不是重点
def __init__(self, *args, **kwargs):
del args, kwargs
# The fields of a `namedtuple` are filled in the `__new__` method.
# `__init__` does not accept parameters.
super(GraphsTuple, self).__init__()
self._validate_none_fields()
# 这就用到了_replace()函数,注意只要修改了属性值
# 那么就返回一个新的对象
def replace(self, **kwargs):
output = self._replace(**kwargs) # 返回一个新的实例
output._validate_none_fields() # pylint: disable=protected-access 验证返回的新实例是否满足要求
return output
# 这是为了针对tensorflow1版本的函数
# 返回一个拥有相同属性的对象,但是它的属性值是输入的大小和类型
def map(self, field_fn, fields=GRAPH_FEATURE_FIELDS): # 对每个键应用函数
"""Applies `field_fn` to the fields `fields` of the instance.
`field_fn` is applied exactly once per field in `fields`. The result must
satisfy the `GraphsTuple` requirement w.r.t. `None` fields, i.e. the
`SENDERS` cannot be `None` if the `EDGES` or `RECEIVERS` are not `None`,
etc.
Args:
field_fn: A callable that take a single argument.
fields: (iterable of `str`). An iterable of the fields to apply
`field_fn` to.
Returns:
A copy of the instance, with the fields in `fields` replaced by the result
of applying `field_fn` to them.
"""
return self.replace(**{k: field_fn(getattr(self, k)) for k in fields}) # getattr(self, k) 获取的是键值对中的值, k表示键
到此这篇关于详解Python中namedtuple的使用的文章就介绍到这了,更多相关python namedtuple的使用内容请搜索云海天教程以前的文章或继续浏览下面的相关文章希望大家以后多多支持云海天教程!
python namedtuple用法_详解Python中namedtuple的使用相关推荐
- [转载] python中for语句用法_详解Python中for循环的使用_python
参考链接: 在Python中将else条件语句与for循环一起使用 这篇文章主要介绍了Python中for循环的使用,来自于IBM官方网站技术文档,需要的朋友可以参考下 for 循环 本系列前面 &q ...
- python中for语句用法_详解Python中for循环的使用_python
这篇文章主要介绍了Python中for循环的使用,来自于IBM官方网站技术文档,需要的朋友可以参考下 for 循环 本系列前面 "探索 Python,第 5 部分:用 Python 编程&q ...
- python中setattr用法_详解Python的hasattr() getattr() setattr() 函数使用方法
hasattr(object, name) 判断一个对象里面是否有name属性或者name方法,返回BOOL值,有name特性返回True, 否则返回False. 需要注意的是name要用括号括起来 ...
- python操作目录_详解python中的文件与目录操作
详解python中的文件与目录操作 一 获得当前路径 1.代码1 >>>import os >>>print('Current directory is ',os. ...
- python xlrd安装_详解python中xlrd包的安装与处理Excel表格
一.安装xlrd 地址 下载后,使用 pip install .whl安装即好. 查看帮助: >>> import xlrd >>> help(xlrd) Help ...
- python gil 解除_详解Python中的GIL(全局解释器锁)详解及解决GIL的几种方案
先看一道GIL面试题: 描述Python GIL的概念, 以及它对python多线程的影响?编写一个多线程抓取网页的程序,并阐明多线程抓取程序是否可比单线程性能有提升,并解释原因. GIL:又叫全局解 ...
- python归一化处理_详解python实现数据归一化处理的方式:(0,1)标准化
在机器学习过程中,对数据的处理过程中,常常需要对数据进行归一化处理,下面介绍(0, 1)标准化的方式,简单的说,其功能就是将预处理的数据的数值范围按一定关系"压缩"到(0,1)的范 ...
- python制作界面_详解python做UI界面的方法
详解python做UI界面的方法 更新时间:2019年02月27日 14:44:34 投稿:laozhang 在本文里我们给大家整理了关于python做UI界面的方法和具体步骤,对此有需要的朋友们可以 ...
- python列表拆包_详解python 拆包可迭代数据如tuple, list
详解python 拆包可迭代数据如tuple, list 拆包是指将一个结构中的数据拆分为多个单独变量中. 以元组为例: >>> a = ('windows', 10, 25.1, ...
最新文章
- 天翼云从业认证(4.11)天翼云物流行业解决方案
- onethink二级导航调用
- WebSphere应用程序服务器Web容器设置
- Maven精选系列--继承与聚合
- JMeter插件模拟发送UDP请求:UDP sampler
- 用GIF展现程序员的生活二
- 如何用matlab分析代谢,代谢流分析工具-CellNetAnalyzer
- java调用MySQL脚本_Java调用SQL脚本执行常用的方法示例
- 面试常考,项目易错!C/C++中的字节对齐
- linux libaio介绍
- 机械键盘POKER2的硬编程
- linux查看程序bss段,LINUX下目标文件的BSS段、数据段、代码段
- Redis 实现搜索关键词自动补全
- notepad++ 分隔符SOH,在Linux中具体的对应字符
- sublime3怎么设置中文很简单
- AI顶会ACL发榜,腾讯30篇论文入选
- 最大流算法之一——EK算法
- mysql vacuum_PostgreSQL中快速对系统表实现vacuum full
- DataGrip 初级与高级教程(仅提供链接)
- xinxin - 蛋蛋大作战