namedtuple使用示例

namedtuple的简单使用

示例代码如下(namedtuple1.py):

#! /usr/bin/env python
#-*- coding:utf-8 -*-

from collections import namedtuple

Student = namedtuple('Student',['id','name','score'],verbose=False)

s1 = Student(1,'s1',81)
print s1
s1 = s1._replace(id=123)
print s1
a,b,c = s1
print a,b,c
print s1.id,s1.name,s1.score

arrTest = [(1,'test1',90),(2,'test2',95)]
for s in arrTest :
    stu = Student._make(s)
    print stu

运行效果如下:

$ python namedtuple1.py
Student(id=1, name='s1', score=81)
Student(id=123, name='s1', score=81)
123 s1 81
123 s1 81
Student(id=1, name='test1', score=90)
Student(id=2, name='test2', score=95)

该代码的github地址: https://github.com/mike-zhang/pyExamples/blob/master/dataStructure/namedtuple_examples/namedtuple1.py