Python中的命名元组(namedtuple)及其用途详解

Python中有一种特殊的元组叫做命名元组,英文名叫namedtuple。

为什么要用命名元组呢?

思考下面的问题:

如何设计数据结构承载一个五维的数据,如一个学生的基本信息?

方法有二:

1. Python是面向对象语言,可以使用class,定义一个学生类,将五维信息作为属性,这是一个重量级的做法。或者说,是一个自定义的数据结构。也是比较通用的方法。

2. 使用tuple,存储五维数据,轻量级。例如:student = ('xiaowang','00001','male',22,99)

        但是这样的做法有两个弊端:(1)索引值难记,难对应。(2).无法表达元素的含义,只能事先约定。

于是,Python创造一个新的数据类型,一种特殊的元组,命名元组(namedtuple)。

值的含义被命名,表述清楚,使用’.’符引用 。

同时,兼具tuple特性,轻量级,仍然可以使用索引。

龟叔:“不要过度的自己去构建数据结构,尽量去使用命名元组 (named tuple) 而不是对象,尽量使用简单的属性域,因为内置数据类型是你最好的朋友。”

可以定义一个命名元组对象student_info用来存储一个五维的学生信息数据。

from collections import namedtuple
# 命名元组对象student_info
student_info = namedtuple('stud_info','name, id, gender, age, score')
# 使用student_info对象对studinf进行赋值
studinf = student_info(name = 'xiaowang', id = '00001', gender = 'male', age = 22, score = 99)
print("name:{}, id:{}, gender:{}, age:{}, score:{}".format(studinf[0],studinf[1],studinf[2],studinf[3],studinf[4]))

也可以用"."来引用属性

from collections import namedtuple
# 命名元组对象student_info
student_info = namedtuple('stud_info','name, id, gender, age, score')
# 使用student_info对象对studinf进行赋值
studinf = student_info(name = 'xiaowang', id = '00001', gender = 'male', age = 22, score = 99)
print("name:{}, id:{}, gender:{}, age:{}, score:{}".format(studinf.name,studinf.id,studinf.gender,studinf.age,studinf.score))

可以使用_make方法对命名元组整体赋值。

from collections import namedtuple
# 命名元组对象student_info
student_info = namedtuple('stud_info','name, id, gender, age, score')
value = ['xiaoli','00002','female',23,100]
studinf = student_info._make(value)
print("name:{}, id:{}, gender:{}, age:{}, score:{}".format(studinf.name,studinf.id,studinf.gender,studinf.age,studinf.score))

可以使用_replace方法修改命名元组的元素值,生成新命名元组。

from collections import namedtuple
# 命名元组对象student_info
student_info = namedtuple('stud_info','name, id, gender, age, score')
# 使用student_info对象对studinf进行赋值
studinf = student_info(name = 'xiaowang', id = '00001', gender = 'male', age = 22, score = 99)
newstud = studinf._replace(name = 'xiaozhao', id = '00003')
print(newstud)
print(studinf)

 注意看,studinf是否有改变。 初始化时的’stud_info’在输出的时候体现。

命名元组的终极实例

从csv文件中导入数据

 依次显示出来。

from collections import namedtuple
import csv
student_info = namedtuple('stud_info','name, id, gender, age, score')
for studinfs in map(student_info._make, csv.reader(open("D:\\students.csv", "r"))):
    print(studinfs)

学会了就点个赞吧。

物联沃分享整理
物联沃-IOTWORD物联网 » Python中的命名元组(namedtuple)及其用途详解

发表评论