详解Python中namedtuple的使用

作者:coolsunxu 时间:2022-05-11 01:29:00 

   namedtuple是Python中存储数据类型,比较常见的数据类型还有有list和tuple数据类型。相比于list,tuple中的元素不可修改,在映射中可以当键使用。

     namedtuple:

namedtuple类位于collections模块,有了namedtuple后通过属性访问数据能够让我们的代码更加的直观更好维护。
namedtuple能够用来创建类似于元祖的数据类型,除了能够用索引来访问数据,能够迭代,还能够方便的通过属性名来访问数据。

接下来通过本文给大家分享python namedtuple()的使用,一起看看吧!

基本定义

collections.namedtuple(typenamefield_names*rename=Falsedefaults=Nonemodule=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)

classmethod somenamedtuple._make(iterable)

(1)从一个序列或者可迭代对象中直接对field_names中的属性直接赋值,返回一个对象


t = [11, 22] # 列表 list
p = Point._make(t) # 从列表中直接赋值,返回对象
print(Point(x=11, y=22))
# Point(x=11, y=22)

classmethod somenamedtuple._asdict()

(1)之前也说过了,说它是元组,感觉更像一个带名字的字典

(2)我们也可以直接使用_asdict()将它解析为一个字典dict


p = Point(x=11, y=22) # 新建一个对象
d = p._asdict() # 解析并返回一个字典对象
print(d)
# {'x': 11, 'y': 22}

classmethod somenamedtuple._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)

classmethod somenamedtuple._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)

classmethod somenamedtuple._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表示键

来源:https://blog.csdn.net/coolsunxu/article/details/105764101

标签:python,namedtuple
0
投稿

猜你喜欢

  • Python基于pillow库实现生成图片水印

    2021-08-01 10:45:38
  • Python实现自动驾驶训练模型

    2023-07-28 18:45:29
  • python买卖股票的最佳时机(基于贪心/蛮力算法)

    2022-12-26 14:44:24
  • Python处理时间日期坐标轴过程详解

    2021-04-28 08:05:27
  • ASP函数指针试探-GetRef

    2009-10-12 12:39:00
  • Python使用JSON库解析JSON数据的方法

    2021-09-24 13:35:10
  • 10个糟糕的IE Bug及其修复

    2010-05-13 16:26:00
  • Web设计色彩速查表

    2009-12-21 16:24:00
  • 浅析Python 实现一个自动化翻译和替换的工具

    2021-12-03 20:48:25
  • python如何提升爬虫效率

    2021-12-17 22:18:24
  • 工程师必须了解的LRU缓存淘汰算法以及python实现过程

    2023-05-22 22:46:00
  • 用Python抢火车票的简单小程序实现解析

    2023-09-06 06:31:28
  • numpy数组的重塑和转置实现

    2022-11-10 10:43:18
  • python类的继承实例详解

    2021-04-10 07:22:33
  • 初步认识Python中的列表与位运算符

    2022-06-28 18:10:51
  • pytorch Dropout过拟合的操作

    2023-11-26 16:12:18
  • 18个超棒的Web和移动应用开发框架

    2011-03-31 17:04:00
  • 给验证码增加干扰的杂点

    2008-05-16 11:34:00
  • 分析python服务器拒绝服务攻击代码

    2021-07-21 20:47:29
  • Pytorch框架实现mnist手写库识别(与tensorflow对比)

    2022-07-30 00:41:42
  • asp之家 网络编程 m.aspxhome.com