Home > Article > Backend Development > Example of using namedtuple structure in Python's collections module
namedtuple is a named tuple, more like a struct in C language. The general tuple is (item1, item2, item3,...). All items can only be accessed according to index and have no clear names. However, namedtuple names these items in advance so that they can be accessed easily in the future.
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 also provides _make to create new instances from iterable objects:
coordinate._make([10,20])
Let’s give another example:
# -*- 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
Result:
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/