python学习笔记——为元组中的每个元素命名

python学习笔记——为元组中的每个元素命名_第1张图片

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



你可能感兴趣的:(Python)