pythonnamedtuple定义类型_详解Python中namedtuple的使用
namedtuple是Python中存儲(chǔ)數(shù)據(jù)類型,比較常見(jiàn)的數(shù)據(jù)類型還有有l(wèi)ist和tuple數(shù)據(jù)類型。相比于list,tuple中的元素不可修改,在映射中可以當(dāng)鍵使用。
namedtuple:
namedtuple類位于collections模塊,有了namedtuple后通過(guò)屬性訪問(wèn)數(shù)據(jù)能夠讓我們的代碼更加的直觀更好維護(hù)。
namedtuple能夠用來(lái)創(chuàng)建類似于元祖的數(shù)據(jù)類型,除了能夠用索引來(lái)訪問(wèn)數(shù)據(jù),能夠迭代,還能夠方便的通過(guò)屬性名來(lái)訪問(wèn)數(shù)據(jù)。
接下來(lái)通過(guò)本文給大家分享python namedtuple()的使用,一起看看吧!
基本定義
collections.namedtuple(typename,?field_names,?*,?rename=False,?defaults=None,?module=None)
(1)返回一個(gè)名為typename的新元組子類
(2)新的子類用于創(chuàng)建類似元組的對(duì)象,這些對(duì)象具有可通過(guò)屬性查找訪問(wèn)的字段以及可索引和可??迭代的字段field_names
typename
(1)typename表示這個(gè)子類的名字,比如C++、python、Java中的類名
field_names
(1)field_names是一個(gè)字符串序列,例如['x','y']
(2)field_names可以是單個(gè)字符串,每個(gè)字段名都用空格或逗號(hào)分隔,例如'x y'或'x,y'
others
(1)其它的參數(shù)并不常用,這里不再介紹啦
基本樣例
from collections import namedtuple
# 基本例子
Point = namedtuple('Point',['x','y']) # 類名為Point,屬性有'x'和'y'
p = Point(11, y=22) # 用位置或關(guān)鍵字參數(shù)實(shí)例化,因?yàn)?#39;x'在'y'前,所以x=11,和函數(shù)參數(shù)賦值一樣的
print(p[0]+p[1]) # 我們也可以使用下標(biāo)來(lái)訪問(wèn)
# 33
x, y = p # 也可以像一個(gè)元組那樣解析
print(x,y)
# (11, 22)
print(p.x+p.y) # 也可以通過(guò)屬性名來(lái)訪問(wèn)
# 33
print(p) # 通過(guò)內(nèi)置的__repr__函數(shù),顯示該對(duì)象的信息
# Point(x=11, y=22)
classmethodsomenamedtuple._make(iterable)
(1)從一個(gè)序列或者可迭代對(duì)象中直接對(duì)field_names中的屬性直接賦值,返回一個(gè)對(duì)象
t = [11, 22] # 列表 list
p = Point._make(t) # 從列表中直接賦值,返回對(duì)象
print(Point(x=11, y=22))
# Point(x=11, y=22)
classmethodsomenamedtuple._asdict()
(1)之前也說(shuō)過(guò)了,說(shuō)它是元組,感覺(jué)更像一個(gè)帶名字的字典
(2)我們也可以直接使用_asdict()將它解析為一個(gè)字典dict
p = Point(x=11, y=22) # 新建一個(gè)對(duì)象
d = p._asdict() # 解析并返回一個(gè)字典對(duì)象
print(d)
# {'x': 11, 'y': 22}
classmethodsomenamedtuple._replace(**kwargs)
(1)這是對(duì)某些屬性的值,進(jìn)行修改的,從replace這個(gè)單詞就可以看出來(lái)
(2)注意該函數(shù)返回的是一個(gè)新的對(duì)象,而不是對(duì)原始對(duì)象進(jìn)行修改
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 新的對(duì)象
print(p)
# Point(x=11, y=22)
print(d)
# Point(x=33, y=22)
classmethodsomenamedtuple._fields
(1)該方法返回該對(duì)象的所有屬性名,以元組的形式
(2)因?yàn)槭窃M,因此支持加法操作
print(p._fields) # 查看屬性名
# ('x', 'y')
Color = namedtuple('Color', 'red green blue')
Pixel = namedtuple('Pixel', Point._fields + Color._fields) # 新建一個(gè)子類,使用多個(gè)屬性名
q = Pixel(11, 22, 128, 255, 0)
print(q)
classmethodsomenamedtuple._field_defaults
(1)該方法是python3.8新增的函數(shù),因?yàn)槲业陌姹臼?.6,無(wú)法驗(yàn)證其正確性
(2)下面給出官方的示例
Account = namedtuple('Account', ['type', 'balance'], defaults=[0])
print(Account._field_defaults)
#{'balance': 0}
print(Account('premium'))
#Account(type='premium', balance=0)
getattr()函數(shù)
(1)用來(lái)獲得屬性的值
print(getattr(p, 'x'))
# 11
字典創(chuàng)建namedtuple()
(1)從字典來(lái)構(gòu)建namedtuple的對(duì)象
d = {'x': 11, 'y': 22} # 字典
p = Point(**d) # 雙星號(hào)是重點(diǎn)
print(p)
# Point(x=11, y=22)
CSV OR Sqlite3
(1)同樣可以將從csv文件或者數(shù)據(jù)庫(kù)中讀取的文件存儲(chǔ)到namedtuple中
(2)這里每次存的都是一行的內(nèi)容
EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, paygrade')
import csv
for emp in map(EmployeeRecord._make, csv.reader(open("employees.csv", "r"))):
# 這里每行返回一個(gè)對(duì)象 注意!
print(emp.name, emp.title)
import sqlite3
conn = sqlite3.connect('/companydata') # 連接數(shù)據(jù)庫(kù)
cursor = conn.cursor()
cursor.execute('SELECT name, age, title, department, paygrade FROM employees')
for emp in map(EmployeeRecord._make, cursor.fetchall()):
# 每行返回一個(gè)對(duì)象 注意!
print(emp.name, emp.title)
類的繼承
(1)接下來(lái)用deepmind的開(kāi)源項(xiàng)目graph_nets中的一段代碼來(lái)介紹
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)):
# 這個(gè)函數(shù)用來(lái)判斷依賴是否滿足,和我們的namedtuple關(guān)系不大
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")
# 用來(lái)初始化一些參數(shù) 不是重點(diǎn)
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()函數(shù),注意只要修改了屬性值
# 那么就返回一個(gè)新的對(duì)象
def replace(self, **kwargs):
output = self._replace(**kwargs) # 返回一個(gè)新的實(shí)例
output._validate_none_fields() # pylint: disable=protected-access 驗(yàn)證返回的新實(shí)例是否滿足要求
return output
# 這是為了針對(duì)tensorflow1版本的函數(shù)
# 返回一個(gè)擁有相同屬性的對(duì)象,但是它的屬性值是輸入的大小和類型
def map(self, field_fn, fields=GRAPH_FEATURE_FIELDS): # 對(duì)每個(gè)鍵應(yīng)用函數(shù)
"""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) 獲取的是鍵值對(duì)中的值, k表示鍵
到此這篇關(guān)于詳解Python中namedtuple的使用的文章就介紹到這了,更多相關(guān)python namedtuple的使用內(nèi)容請(qǐng)搜索我們以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持我們!
本文標(biāo)題: 詳解Python中namedtuple的使用
本文地址: http://www.cppcns.com/jiaoben/python/310459.html
總結(jié)
以上是生活随笔為你收集整理的pythonnamedtuple定义类型_详解Python中namedtuple的使用的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 高中生学python培养思维能力_基于培
- 下一篇: python词性标注_文本分类的词性标注