元組中元素的操作一般使用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