python學習筆記——爲元組中的每個元素命名

元組中元素的操作一般使用index獲取

student = ('jim',16,'male','[email protected]')
print(student[0])
jim
print(student[2])
male

進階方法:

1 / 使用命名變量獲取index,然後操作變量

name,age,sex,email = range(4)
student = ('jim',16,'male','[email protected]')
print(name,age,sex,email)
0 1 2 3
print(student[name])
jim
print(student[email])
[email protected]
2 / 使用標準庫中的collections.namedtuple 替代內置tuple

namedtuple相當於類的工廠

namedtuple可以很方便地定義一種數據類型,它具備tuple的不變性,又可以根據屬性來引用,使用十分方便。

from collections import namedtuple
student = namedtuple('student',['name','age','sex','email'])
student('jim',16,'male','[email protected]')
Out[42]: 
student(name='jim', age=16, sex='male', email='[email protected]')
s = student('jim',16,'male','[email protected]')
s.name
Out[44]: 
'jim'
s.email
Out[45]: 
'[email protected]'
isinstance(s,tuple)
Out[46]: 
True



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章