源码解释:

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 tuple33>>> x, y = p                        # unpack like a regular tuple>>> x, y(11, 22)>>> p.x + p.y                       # fields also accessible by name33>>> d = p._asdict()                 # convert to a dictionary>>> d['x']11>>> Point(**d)                      # convert from a dictionaryPoint(x=11, y=22)>>> p._replace(x=100)               # _replace() is like str.replace() but targets named fieldsPoint(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 namedtuplePerson = 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 namedtuplecard = 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 namedtupleperson = 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 namedtuplecourse = 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 namedtupleperson = 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 namedtupleperson = 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 namedtupleperson = 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 namedtupleperson = 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 namedtupleperson = 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 namedtuplePoint = namedtuple('Point', ['x', 'y'])
p = Point(4, 5)
print(p)class Point(namedtuple('Point', ['x', 'y'])):__slots__ = ()@propertydef hypot(self):return self.x + self.ydef hypot2(self):return self.x + self.ydef __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 namedtuplePoint = 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 = xself.y = yo = Point2(33, 44)
print(o)
print(o.x, o.y)

运行结果:

python中namedtuple函数用法详解相关推荐

  1. python中setattr()函数用法详解

    setattr() 函数对应函数 getattr(),用于设置属性值,该属性不一定是存在的. getattr()用法详见博文:python中getattr()函数用法详解_IT之一小佬的博客-CSDN ...

  2. python中repr()函数用法详解

    在 Python 中要将某一类型的变量或者常量转换为字符串对象通常有两种方法,即str() 或者 repr() . str()和repr()区别: 函数str( )将其转化成为适于人阅读的前端样式文本 ...

  3. python中getattr()函数用法详解

    getattr() 函数用于返回一个对象属性值. def getattr(object, name, default=None): # known special case of getattr&qu ...

  4. python中isinstance()函数用法详解

    isinstance()用来判断一个对象是否是一个已知的类型,isinstance()函数的语法如下: isinstance(object,classtype) object -- 实例对象. cla ...

  5. python中reduce()函数用法详解

    reduce()源码: def reduce(function, sequence, initial=None): # real signature unknown; restored from __ ...

  6. python中any()函数用法详解

    any()源码解析: def any(*args, **kwargs): # real signature unknown"""Return True if bool(x ...

  7. Python中strip()函数用法详解

    strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列. 移除首尾存在于strip('str_list') str_list中任何的字符. 如图所示,只要字符串中收尾存在着1 ...

  8. python中hasattr()函数用法详解

    hasattr() 函数用来判断某个类实例对象是否包含指定名称的属性或方法. 无论是属性名还是方法名,都在 hasattr() 函数的匹配范围内. 通过该函数判断实例对象是否包含该名称的属性或方法,但 ...

  9. python中的super用法详解_Python中super函数用法实例分析

    本文实例讲述了python中super函数用法.分享给大家供大家参考,具体如下: 这是个高大上的函数,在python装13手册里面介绍过多使用可显得自己是高手 23333. 但其实他还是很重要的. 简 ...

最新文章

  1. # select sort 选择排序
  2. iBATIS In Action:执行非查询语句(二)
  3. MyBatis3 用log4j在控制台输出 SQL----亲测,真实可用
  4. linux es数据库 head,centos7安装Elasticsearch及Es-head插件详细教程(图文)
  5. 996是人类社会的倒退
  6. NYOJ Dinner
  7. python入侵电脑教程_Python外星人入侵问题求助?python网站入侵视频教程
  8. 李践《行动日志——目标管理》观后感
  9. 数组根据某个条件筛选出符合的数据,生成一个新的数组
  10. Argo Rollouts 实现蓝绿/金丝雀发布
  11. 2017计算机二级ms office高级应用成绩查询
  12. k短路(HDU6705)
  13. 2022081班李亚楠20220901
  14. Truck History prime
  15. C++ MFC万能的类向导
  16. arm-linux移植zmodem命令lrz,lsz
  17. 卡尔曼及扩展卡尔曼滤波详细推导-来自DR_CAN视频
  18. C# 创建Excel,读取mdb数据库,写入Excel数据,获取mdb中所有表格名字,选择多个文件
  19. arcgis制作兴趣点分布图
  20. QQ空间爬虫分享(一天可抓取 400 万条数据)

热门文章

  1. 日本感情电影 -- 情书
  2. 概率统计·参数估计【矩估计、极大似然估计、无偏性、有效性、相合性】
  3. win10 程序最小化不在任务栏了?在左下角
  4. Fiddler 微信小程序抓包
  5. 2019 Revit二次开发企业
  6. Chrome谷歌浏览器的快捷键:
  7. pr制作马赛克的效果,动态光效素材应用,
  8. Mesos | 1.3.2 webui static 界面代码分析
  9. 视频画面裁剪怎么弄?分享几个实用技巧
  10. docker安装和portainer安装