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

    xiaoxiao2021-03-25  206

    元组中元素的操作一般使用index获取

    student = ('jim',16,'male','jim8721@gmail.com') print(student[0]) jim print(student[2]) male 进阶方法:

    1 / 使用命名变量获取index,然后操作变量

    name,age,sex,email = range(4) student = ('jim',16,'male','jim8721@gmail.com') print(name,age,sex,email) 0 1 2 3 print(student[name]) jim print(student[email]) jim8721@gmail.com 2 / 使用标准库中的collections.namedtuple 替代内置tuple

    namedtuple相当于类的工厂

    namedtuple可以很方便地定义一种数据类型,它具备tuple的不变性,又可以根据属性来引用,使用十分方便。

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

    转载请注明原文地址: https://ju.6miu.com/read-1577.html

    最新回复(0)