1. 程式人生 > >python_如何為元組中每個元素命名

python_如何為元組中每個元素命名

進行 port 數據 大量 程序 問題 什麽 log python

學生信息系統:

(名字,年齡,性別,郵箱地址)

為了減少存儲開支,每個學生的信息都以一個元組形式存放

如:

(‘tom‘, 18,‘male‘,[email protected] )

(‘jom‘, 18,‘mal‘,[email protected] ) .......

這種方式存放,如何訪問呢?

普通方法:

#!/usr/bin/python3
student = (‘tom‘, 18, ‘male‘, ‘tom @ qq.com‘ )
print(student[0])
if student[1] > 12:
    ...
if student[2] == ‘male‘:   
    ...

出現問題,程序中存在大量的數字index,可閱讀性太差,無法知道每個數字代替的含義

如何解決這個問題?

方法1:

#!/usr/bin/python3
# 給數字帶上含義,和元組中一一對應 name, age, sex, email = 0, 1, 2, 3 # 高級:name, age, sex, email = range(4) student = (‘tom‘, 18, ‘male‘, ‘tom @ qq.com‘ ) print(student[name]) if student[age] > 12: print(‘True‘) if student[sex] == ‘male‘: print(‘True‘)

這樣就直白多了,看名字就知道取什麽元素

方法2:

  通過 collections庫的 nametuple模塊

#!/usr/bin/python3

from collections import namedtuple

# 生成一個Student類
Student = namedtuple(‘Student‘, [‘name‘, ‘age‘, ‘sex‘, ‘email‘])

# 生成一條信息對象
s = Student(‘tom‘, 18, ‘male‘, [email protected])

# 通過類對象進行取數據
print(s.name, s.age, s.sex, s.email)

python_如何為元組中每個元素命名