当前位置: 首页 > 编程笔记 >

Python的collections模块中namedtuple结构使用示例

赏开宇
2023-03-14
本文向大家介绍Python的collections模块中namedtuple结构使用示例,包括了Python的collections模块中namedtuple结构使用示例的使用技巧和注意事项,需要的朋友参考一下

namedtuple 就是命名的 tuple,比较像 C 语言中 struct。一般情况下的 tuple 是 (item1, item2, item3,...),所有的 item 都只能按照 index 访问,没有明确的称呼,而 namedtuple 就是事先把这些 item 命名,以后可以方便访问。

from collections import namedtuple


# 初始化需要两个参数,第一个是 name,第二个参数是所有 item 名字的列表。
coordinate = namedtuple('Coordinate', ['x', 'y'])

c = coordinate(10, 20)
# or
c = coordinate(x=10, y=20)

c.x == c[0]
c.y == c[1]
x, y = c

namedtuple 还提供了 _make 从 iterable 对象中创建新的实例:

coordinate._make([10,20])

再来举个栗子:

# -*- coding: utf-8 -*-
"""
比如我们用户拥有一个这样的数据结构,每一个对象是拥有三个元素的tuple。
使用namedtuple方法就可以方便的通过tuple来生成可读性更高也更好用的数据结构。
"""
from collections import namedtuple
websites = [
 ('Sohu', 'http://www.google.com/', u'张朝阳'),
 ('Sina', 'http://www.sina.com.cn/', u'王志东'),
 ('163', 'http://www.163.com/', u'丁磊')
]
Website = namedtuple('Website', ['name', 'url', 'founder'])
for website in websites:
 website = Website._make(website)
 print website
 print website[0], website.url

结果:

Website(name='Sohu', url='http://www.google.com/', founder=u'\u5f20\u671d\u9633')
Sohu http://www.google.com/
Website(name='Sina', url='http://www.sina.com.cn/', founder=u'\u738b\u5fd7\u4e1c')
Sina http://www.sina.com.cn/
Website(name='163', url='http://www.163.com/', founder=u'\u4e01\u78ca')
163 http://www.163.com/
 类似资料:
  • 本文向大家介绍简单掌握Python的Collections模块中counter结构的用法,包括了简单掌握Python的Collections模块中counter结构的用法的使用技巧和注意事项,需要的朋友参考一下 counter 是一种特殊的字典,主要方便用来计数,key 是要计数的 item,value 保存的是个数。 初始化可以传入三种类型的参数:字典,其他 iterable 的数据类型,还有命

  • 本文向大家介绍详解Python的collections模块中的deque双端队列结构,包括了详解Python的collections模块中的deque双端队列结构的使用技巧和注意事项,需要的朋友参考一下 deque 是 double-ended queue的缩写,类似于 list,不过提供了在两端插入和删除的操作。 appendleft 在列表左侧插入 popleft 弹出列表左侧的值 exten

  • 本文向大家介绍使用Python的内建模块collections的教程,包括了使用Python的内建模块collections的教程的使用技巧和注意事项,需要的朋友参考一下 collections是Python内建的一个集合模块,提供了许多有用的集合类。 namedtuple 我们知道tuple可以表示不变集合,例如,一个点的二维坐标就可以表示成: 但是,看到(1, 2),很难看出这个tuple是用

  • author: Wuxiaolong 在Python中有一些内置的数据类型,比如int, str, list, tuple, dict等。Python的collections模块在这些内置数据类型的基础上,提供了几个额外的数据类型:namedtuple, defaultdict, deque, Counter, OrderedDict等,其中defaultdict和namedtuple是两个很实用

  • 本文向大家介绍Python中的defaultdict模块和namedtuple模块的简单入门指南,包括了Python中的defaultdict模块和namedtuple模块的简单入门指南的使用技巧和注意事项,需要的朋友参考一下 在Python中有一些内置的数据类型,比如int, str, list, tuple, dict等。Python的collections模块在这些内置数据类型的基础上,提供

  • 本文向大家介绍Python hashlib模块的使用示例,包括了Python hashlib模块的使用示例的使用技巧和注意事项,需要的朋友参考一下 一.hashlib模块 用于加密相关的操作,3.x里代替了md5模块和sha模块,主要提供 :SHA1,SHA224,SHA256,SHA384,SHA512,MD5算法。 1.使用hashlib模块进行MD5加密。 注:hashlib.md5():创