python 命名元組 namedtuple

python命名元組

利用 collections 模塊中的 namedtuple 函數

from collections import namedtuple
namedtuple(typename, field_names) 

typename:命名元組的名稱;
field_names: 元祖中元素的名稱此字段有多種表達方式

三種命名元組定義方式

Student = namedtuple("Student",'id name age sex love')
Student = namedtuple("Student",'id,name,age,sex,love')
Student = namedtuple("Student",['id','name','age','sex','love'])

訪問元祖對象中的元素時可以使用逗號操作符(.)讀取對象中的元素

s = Student(*(data.split()))
print(s.id)

完整示例

from collections import namedtuple

Student = namedtuple("Student",'id name age sex love')

data = "1 fy 18 male football"

#['1', 'fy', '18', 'male', 'football']
print(data.split())

#1 fy 18 male football
print(*(data.split()))

#Student(id='1', name='fy', age='18', sex='male', love='football')
# 解引用後傳遞給創建元組的調用,而不用解析每一個字段併爲每一個字段進行賦值
print(Student(*(data.split())))

#訪問元祖對象中的元素時可以使用逗號操作符(.)讀取對象中的元素,而不必像原始元組中,需要記錄下標s[2]代表的元素含義
s = Student(*(data.split()))
print(s.id)
print(s.name)
print(s.age)
print(s.sex)
print(s.love)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章