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

     namedtuple:

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

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

基本定义

collections.namedtuple(typenamefield_names*rename=Falsedefaults=Nonemodule=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表示键
华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com

《魔兽世界》大逃杀!60人新游玩模式《强袭风暴》3月21日上线

暴雪近日发布了《魔兽世界》10.2.6 更新内容,新游玩模式《强袭风暴》即将于3月21 日在亚服上线,届时玩家将前往阿拉希高地展开一场 60 人大逃杀对战。

艾泽拉斯的冒险者已经征服了艾泽拉斯的大地及遥远的彼岸。他们在对抗世界上最致命的敌人时展现出过人的手腕,并且成功阻止终结宇宙等级的威胁。当他们在为即将于《魔兽世界》资料片《地心之战》中来袭的萨拉塔斯势力做战斗准备时,他们还需要在熟悉的阿拉希高地面对一个全新的敌人──那就是彼此。在《巨龙崛起》10.2.6 更新的《强袭风暴》中,玩家将会进入一个全新的海盗主题大逃杀式限时活动,其中包含极高的风险和史诗级的奖励。

《强袭风暴》不是普通的战场,作为一个独立于主游戏之外的活动,玩家可以用大逃杀的风格来体验《魔兽世界》,不分职业、不分装备(除了你在赛局中捡到的),光是技巧和战略的强弱之分就能决定出谁才是能坚持到最后的赢家。本次活动将会开放单人和双人模式,玩家在加入海盗主题的预赛大厅区域前,可以从强袭风暴角色画面新增好友。游玩游戏将可以累计名望轨迹,《巨龙崛起》和《魔兽世界:巫妖王之怒 经典版》的玩家都可以获得奖励。