Namedtuple is named tuple, more like struct in C language. In general, the tuple is (item1, item2, Item3,...), all the item can only be accessed according to the index, there is no clear name, and Namedtuple is in advance of these item name, can be easily accessed later.
From collections import Namedtuple
# Initialization requires two parameters, the first is name, and the second parameter is a list of all item names.
coordinate = namedtuple (' coordinate ', [' X ', ' y '])
c = Coordinate (M)
# or
c = Coordinate (x=10, y=20)
c.x = = C[0]
c.y = = c[1]
x, y = C
Namedtuple also provides _make to create a new instance from the Iterable object:
Coordinate._make ([10,20])
One more chestnut:
#-*-Coding:utf-8-*-
"" "
such as our users have a data structure, each object is a tuple with three elements.
using the Namedtuple method makes it easy to generate more readable and better data structures through tuple. "" "from
collections Import namedtuple
websites = [
(' Sohu ', ' http://www.google.com/', U ' Charles Zhang '),
(' Sina ', ' http://www.sina.com.cn/', U ' leverling '),
(' 163 ', ' http://www.163.com/', U ' Ding Lei ')
]
Website = Namedtuple (' Website ', [' name ', ' url ', ' founder ']) for
Website in websites:
Website = Website._make (Website) C14/>print website
print website[0], Website.url
Results:
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/