python中namedtuple函数的用法解析
作者:IT之一小佬 发布时间:2023-08-22 11:03:24
源码解释:
def namedtuple(typename, field_names, *, rename=False, defaults=None, module=None):
"""Returns a new subclass of tuple with named fields.
>>> Point = namedtuple('Point', ['x', 'y'])
>>> Point.__doc__ # docstring for the new class
'Point(x, y)'
>>> p = Point(11, y=22) # instantiate with positional args or keywords
>>> p[0] + p[1] # indexable like a plain tuple
33
>>> x, y = p # unpack like a regular tuple
>>> x, y
(11, 22)
>>> p.x + p.y # fields also accessible by name
33
>>> d = p._asdict() # convert to a dictionary
>>> d['x']
11
>>> Point(**d) # convert from a dictionary
Point(x=11, y=22)
>>> p._replace(x=100) # _replace() is like str.replace() but targets named fields
Point(x=100, y=22)
"""
语法结构:
namedtuple(typename, field_names, *, rename=False, defaults=None, module=None)
typename: 代表新建的一个元组的名字。
field_names: 是元组的内容,是一个类似list的[‘x’,‘y’]
命名元组,使得元组可像列表一样使用key访问(同时可以使用索引访问)。
collections.namedtuple 是一个工厂函数,它可以用来构建一个带字段名的元组和一个有名字的类.
创建一个具名元组需要两个参数,一个是类名,另一个是类的各个字段的名字。
存放在对应字段里的数据要以一串参数的形式传入到构造函数中(注意,元组的构造函数却只接受单一的可迭代对象)。
命名元组还有一些自己专有的属性。最有用的:类属性_fields、类方法 _make(iterable)和实例方法_asdict()。
示例代码1:
from collections import namedtuple
# 定义一个命名元祖city,City类,有name/country/population/coordinates四个字段
city = namedtuple('City', 'name country population coordinates')
tokyo = city('Tokyo', 'JP', 36.933, (35.689, 139.69))
print(tokyo)
# _fields 类属性,返回一个包含这个类所有字段名称的元组
print(city._fields)
# 定义一个命名元祖latLong,LatLong类,有lat/long两个字段
latLong = namedtuple('LatLong', 'lat long')
delhi_data = ('Delhi NCR', 'IN', 21.935, latLong(28.618, 77.208))
# 用 _make() 通过接受一个可迭代对象来生成这个类的一个实例,作用跟City(*delhi_data)相同
delhi = city._make(delhi_data)
# _asdict() 把具名元组以 collections.OrderedDict 的形式返回,可以利用它来把元组里的信息友好地呈现出来。
print(delhi._asdict())
运行结果:
示例代码2:
from collections import namedtuple
Person = namedtuple('Person', ['age', 'height', 'name'])
data2 = [Person(10, 1.4, 'xiaoming'), Person(12, 1.5, 'xiaohong')]
print(data2)
res = data2[0].age
print(res)
res2 = data2[1].name
print(res2)
运行结果:
示例代码3:
from collections import namedtuple
card = namedtuple('Card', ['rank', 'suit']) # 定义一个命名元祖card,Card类,有rank和suit两个字段
class FrenchDeck(object):
ranks = [str(n) for n in range(2, 5)] + list('XYZ')
suits = 'AA BB CC DD'.split() # 生成一个列表,用空格将字符串分隔成列表
def __init__(self):
# 生成一个命名元组组成的列表,将suits、ranks两个列表的元素分别作为命名元组rank、suit的值。
self._cards = [card(rank, suit) for suit in self.suits for rank in self.ranks]
print(self._cards)
# 获取列表的长度
def __len__(self):
return len(self._cards)
# 根据索引取值
def __getitem__(self, item):
return self._cards[item]
f = FrenchDeck()
print(f.__len__())
print(f.__getitem__(3))
运行结果:
示例代码4:
from collections import namedtuple
person = namedtuple('Person', ['first_name', 'last_name'])
p1 = person('san', 'zhang')
print(p1)
print('first item is:', (p1.first_name, p1[0]))
print('second item is', (p1.last_name, p1[1]))
运行结果:
示例代码5: 【_make 从存在的序列或迭代创建实例】
from collections import namedtuple
course = namedtuple('Course', ['course_name', 'classroom', 'teacher', 'course_data'])
math = course('math', 'ERB001', 'Xiaoming', '09-Feb')
print(math)
print(math.course_name, math.course_data)
course_list = [
('computer_science', 'CS001', 'Jack_ma', 'Monday'),
('EE', 'EE001', 'Dr.han', 'Friday'),
('Pyhsics', 'EE001', 'Prof.Chen', 'None')
]
for k in course_list:
course_i = course._make(k)
print(course_i)
运行结果:
示例代码6: 【_asdict 返回一个新的ordereddict,将字段名称映射到对应的值】
from collections import namedtuple
person = namedtuple('Person', ['first_name', 'last_name'])
zhang_san = ('Zhang', 'San')
p = person._make(zhang_san)
print(p)
# 返回的类型不是dict,而是orderedDict
print(p._asdict())
运行结果:
示例代码7: 【_replace 返回一个新的实例,并将指定域替换为新的值】
from collections import namedtuple
person = namedtuple('Person', ['first_name', 'last_name'])
zhang_san = ('Zhang', 'San')
p = person._make(zhang_san)
print(p)
p_replace = p._replace(first_name='Wang')
print(p_replace)
print(p)
p_replace2 = p_replace._replace(first_name='Dong')
print(p_replace2)
运行结果:
示例代码8: 【_fields 返回字段名】
from collections import namedtuple
person = namedtuple('Person', ['first_name', 'last_name'])
zhang_san = ('Zhang', 'San')
p = person._make(zhang_san)
print(p)
print(p._fields)
运行结果:
示例代码9: 【利用fields可以将两个namedtuple组合在一起】
from collections import namedtuple
person = namedtuple('Person', ['first_name', 'last_name'])
print(person._fields)
degree = namedtuple('Degree', 'major degree_class')
print(degree._fields)
person_with_degree = namedtuple('person_with_degree', person._fields + degree._fields)
print(person_with_degree._fields)
zhang_san = person_with_degree('san', 'zhang', 'cs', 'master')
print(zhang_san)
运行结果:
示例代码10: 【field_defaults】
from collections import namedtuple
person = namedtuple('Person', ['first_name', 'last_name'], defaults=['san'])
print(person._fields)
print(person._field_defaults)
print(person('zhang'))
print(person('Li', 'si'))
运行结果:
示例代码11: 【namedtuple是一个类,所以可以通过子类更改功能】
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(4, 5)
print(p)
class Point(namedtuple('Point', ['x', 'y'])):
__slots__ = ()
@property
def hypot(self):
return self.x + self.y
def hypot2(self):
return self.x + self.y
def __str__(self):
return 'result is %.3f' % (self.x + self.y)
aa = Point(4, 5)
print(aa)
print(aa.hypot)
print(aa.hypot2)
运行结果:
示例代码12: 【注意观察两种写法的不同】
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(11, 22)
print(p)
print(p.x, p.y)
# namedtuple本质上等于下面写法
class Point2(object):
def __init__(self, x, y):
self.x = x
self.y = y
o = Point2(33, 44)
print(o)
print(o.x, o.y)
运行结果:
来源:https://blog.csdn.net/weixin_44799217/article/details/126594612


猜你喜欢
- 一,最常见MYSQL最基本的分页方式:select * from content order by id desc limit 0, 10在
- 误区 #1:在服务器故障转移后,正在运行的事务继续执行 这当然是错误的! 每次故障转移都伴随着某种形式的恢复。但是如果当正在执行的事务没有C
- Python安装Graphviz画图器首先,要明确他是一个独立的软件,如果大家用pip的方法装了graphviz可以先卸载pip unins
- 1. 引言如果能够将我们的无序数据快速组织成更易读的格式,对于数据分析非常有帮助。 Python 提供了将某些表格数据类型轻松转换为格式良好
- 本文实例为大家分享了js canvas随机粒子特效的具体代码,供大家参考,具体内容如下前言canvas实现前端的特效美术结果展示代码html
- match()函数的使用。以及从文本中提取数据的方法。在学习re模块的相关函数前应了解正则表达式的特殊字符准备一个要爬取的文本文档:直接从某
- 我们经常会发现网页中的许多数据并不是写死在HTML中的,而是通过js动态载入的。所以也就引出了什么是动态数据的概念,动态数据在这里指的是网页
- 一、什么是七段数码显示器 七段LCD数码显示器
- 当我们拿到一个对象的引用时,如何知道这个对象是什么类型、有哪些方法呢?使用type()首先,我们来判断对象类型,使用type()函数:基本类
- 很多时候关心的是优化SELECT 查询,因为它们是最常用的查询,而且确定怎样优化它们并不总是直截了当。相对来说,将数据装入数据库是直截了当的
- 我写过一个外部模块扩展,现在开始看PHP源码中的mysql扩展,它是可以被集成到PHP内部的,所以应该算是内置的扩展了。 该扩展需要用到my
- 说明本文根据https://github.com/liuchengxu/blockchain-tutorial的内容,用python实现的,
- 本文实例为大家分享了python发邮件精简代码,供大家参考,具体内容如下import smtplibfrom email.mime.text
- 目录一、Go调用C代码的原理二、在Go中使用C语言的类型1、原生类型数值类型指针类型字符串类型数组类型2、自定义类型枚举(enum)结构体(
- 现在的高手真是越来越多,我刚发现一个版主兄竟然在不支持数据库的ISP免费主页上使用数据库,套用QQ聊天的一句话就是:Faint!明明人家IS
- 本文实例为大家分享了python实现录音功能的具体代码,供大家参考,具体内容如下# -*- coding: utf-8 -*-import
- 英文版:File -> settings -> Editor -> File Encodings首先打开设置:文件 -&g
- 很多时候,设计师们都会通过各种渠道去了解用户的需求,然而从这些渠道反馈回来的信息大部分只是用户的期望并不是真正的用户需求,但是很多时候这些期
- mysql查询字段为null的数据navicat查询数据为null的数据varchar字段 默认为(null)所以查询的语句是se
- pycharm sql语句警告产生原因为没有配置数据库,配置数据库,似乎没什么作用那么,直接去掉他的警告提示找到setting->ed