python数据结构-如何为元组中的每个元素命名

如何为元组中的每个元素命名

简述

当对象数据格式固定时,用元组比列表更节省内存空间,

我们使用索引访问元组元素,但是这种访问方式会降低程序的可读性。

举个栗子

对于学生的信息,我们有固定的数据格式,我们可以用元组表示,

但是在我们使用它的时候并不知道stu1[1],stu[2]具体代表什么信息,

这就大大降低了程序的可读性

stu1 = ("tom", 16, "male")

def fun1(stu):
    if stu1[1]:
        pass

    if stu1[2] == 'male':
        pass

fun1(stu1)

那我们怎么提高程序的可读性呢,解决方法如下

定义一系列数值常量或枚举类型

定义一系列数值常量

NAME = 0
AGE = 1
SEX = 2

stu1 = ("tom", 16, "male")

def fun1(stu):
    if stu1[NAME]:
        pass

    if stu1[SEX] == 'male':
        pass

fun1(stu1)

分析:但是这种方式比较低效,我们可以采用元组的拆包

NAME, AGE, SEX = range(3)

stu1 = ("tom", 16, "male")

def fun1(stu):
    if stu1[NAME]:
        pass

    if stu1[SEX] == 'male':
        pass

fun1(stu1)

分析:如果还有一个老师的数据结构,元组的第一项是年龄,第二项是姓名,

如果在程序中有多种数据结构,还使用定义常量的方式,有些常量会冲突,

如果分开对象去定义常量,如STU_NAME, TEA_NAME, STU_AGE, TEA_AGE,这样全局变量太多

一般这种情况我们会使用枚举

枚举

优点:相当于创造了一个名称空间

from enum import IntEnum

class StudentEnum(IntEnum):
    NAME = 0
    AGE = 1
    SEX = 2

stu1 = ("tom", 16, "male")
print(StudentEnum.NAME == 0) #True
print(StudentEnum.AGE == 1) #True
print(isinstance(StudentEnum.NAME, int)) #True

使用标准库中的collections.namedtuple代替内置tuple

优点:

使用元组可以节省空间

提升程序可读性

from collections import namedtuple
Student = namedtuple('Student', ['name', 'age', 'sex'])
stu1 = Student("tom", 16, "male")
print(isinstance(stu1, tuple)) #True
print(stu1.name) #“tom”
print(stu1.age) #16

参考资料:python3实用编程技巧进阶

原文地址:https://www.cnblogs.com/marton/p/10727362.html