1. 程式人生 > 程式設計 >Python 如何提高元組的可讀性

Python 如何提高元組的可讀性

這篇文章主要介紹了Python 如何提高元組的可讀性,文中通過示例程式碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下

假設學生系統中資料為固定格式:(名字,年齡,性別,郵箱)

('jack','16','male','[email protected]')
('eric','17','[email protected]')
('xander','female','[email protected]')

方案一:

from enum import IntEnum
NAME,AGE,SEX,EMAIL=range(4)
s=('jim','[email protected]')
# print(NAME) # 0
class StudentEnum(IntEnum):
  NAME=0
  AGE=1
  SEX=2
  EMAIL=3

print(s[StudentEnum.NAME]) # jim
print(isinstance(StudentEnum.NAME,int)) # True

方案二:

from collections import namedtuple
Student=namedtuple('Student',['name','age','sex','email'])
s2=Student('jim','[email protected]')
s3=Student('eric','[email protected]')

print(s2) # Student(name='jim',age='16',sex='male',email='[email protected]')
print(s3) # Student(name='eric',email='[email protected]')

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。