Python中有一種特殊的元組叫做命名元組,英文名叫namedtuple。
為什么要用命名元組呢?
思考下面的問題:
如何設(shè)計(jì)數(shù)據(jù)結(jié)構(gòu)承載一個五維的數(shù)據(jù),如一個學(xué)生的基本信息?
方法有二:
1. Python是面向?qū)ο笳Z言,可以使用class,定義一個學(xué)生類,將五維信息作為屬性,這是一個重量級的做法?;蛘哒f,是一個自定義的數(shù)據(jù)結(jié)構(gòu)。也是比較通用的方法。
2.?使用tuple,存儲五維數(shù)據(jù),輕量級。例如:student = ('xiaowang','00001','male',22,99)
????????但是這樣的做法有兩個弊端:(1)索引值難記,難對應(yīng)。(2).無法表達(dá)元素的含義,只能事先約定。
于是,Python創(chuàng)造一個新的數(shù)據(jù)類型,一種特殊的元組,命名元組(namedtuple)。
值的含義被命名,表述清楚,使用’.’符引用 。
同時,兼具tuple特性,輕量級,仍然可以使用索引。
龜叔:“不要過度的自己去構(gòu)建數(shù)據(jù)結(jié)構(gòu),盡量去使用命名元組 (named tuple) 而不是對象,盡量使用簡單的屬性域,因?yàn)閮?nèi)置數(shù)據(jù)類型是你最好的朋友?!?/strong>
可以定義一個命名元組對象student_info用來存儲一個五維的學(xué)生信息數(shù)據(jù)。
from collections import namedtuple
# 命名元組對象student_info
student_info = namedtuple('stud_info','name, id, gender, age, score')
# 使用student_info對象對studinf進(jìn)行賦值
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進(jìn)行賦值
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進(jìn)行賦值
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’在輸出的時候體現(xiàn)。
命名元組的終極實(shí)例
從csv文件中導(dǎo)入數(shù)據(jù)
?依次顯示出來。
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)
文章來源:http://www.zghlxwxcb.cn/news/detail-684540.html
學(xué)會了就點(diǎn)個贊吧。文章來源地址http://www.zghlxwxcb.cn/news/detail-684540.html
到了這里,關(guān)于Python中的命名元組(namedtuple)到底是什么東西?干嘛用的?的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!