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)新的子类用于创建类似元组的对象,这些对象具有可通过属性查找访问的字段以及可索引和可"htmlcode">
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表示键
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
更新日志
- 小骆驼-《草原狼2(蓝光CD)》[原抓WAV+CUE]
- 群星《欢迎来到我身边 电影原声专辑》[320K/MP3][105.02MB]
- 群星《欢迎来到我身边 电影原声专辑》[FLAC/分轨][480.9MB]
- 雷婷《梦里蓝天HQⅡ》 2023头版限量编号低速原抓[WAV+CUE][463M]
- 群星《2024好听新歌42》AI调整音效【WAV分轨】
- 王思雨-《思念陪着鸿雁飞》WAV
- 王思雨《喜马拉雅HQ》头版限量编号[WAV+CUE]
- 李健《无时无刻》[WAV+CUE][590M]
- 陈奕迅《酝酿》[WAV分轨][502M]
- 卓依婷《化蝶》2CD[WAV+CUE][1.1G]
- 群星《吉他王(黑胶CD)》[WAV+CUE]
- 齐秦《穿乐(穿越)》[WAV+CUE]
- 发烧珍品《数位CD音响测试-动向效果(九)》【WAV+CUE】
- 邝美云《邝美云精装歌集》[DSF][1.6G]
- 吕方《爱一回伤一回》[WAV+CUE][454M]
 
                     
                    