Example of namedtuple structure usage in Python's collections module _python

Source: Internet
Author: User
Tags data structures

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/

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.