如何為元組中的每個元素命名,提高程式可讀性

2021-08-19 22:39:00 字數 1005 閱讀 2220

1、實際案例

學生資訊系統中資料為固定格式:

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

學生數量很大為了減小儲存開銷,對每個學生資訊用元組表示:

('jim',16,'male','[email protected]'

(li lei',17,'male','[email protected]')

('lucy',16,'female','[email protected]')

訪問時,我們使用引索(index)訪問,大量引索降低程式可讀性,如何解決這個問題?

student = ('jim',16,'male','[email protected]')

#name

print student[0]

#age

if student[1]>=18

2、解決方案

2.1 解決方案一:定義類似與其他語言的列舉型別,也就是定義一系列數值常量

把0、1、2、3賦給變數

student = ('jim',16,'male','[email protected]'

name,age,***,email = xrange(4)

#name

print student[name]

#age

if student[age] >= 18:

# ...

#***

if students[***] == 'male':

#....

2.2 解決方案二:使用標準庫中collenctions.namedtuple替代內建touple,執行結果

from collections import namedtuple

student = namedtuple('student',['name','age','***','email'])

s = student('jim',16,'male','[email protected]')

如何在元組中的每個元素命名,提高程式可讀性

實際案例 如 學生數量很大為了減小儲存開銷,對每個學生資訊用元組表示 jim 16,male jim gmail.com li 17,male li 163.com lucy 16,female lucy qq.com 通常我們採用索引的方式訪問元組,具體操作如下 coding utf 8 stud...

python資料結構 如何為元組中的每個元素命名

當物件資料格式固定時,用元組比列表更節省記憶體空間,我們使用索引訪問元組元素,但是這種訪問方式會降低程式的可讀性。舉個栗子 對於學生的資訊,我們有固定的資料格式,我們可以用元組表示,但是在我們使用它的時候並不知道stu1 1 stu 2 具體代表什麼資訊,這就大大降低了程式的可讀性 stu1 tom...

python中的命名元組namedtuple

namedtuple是繼承自tuple的子類。namedtuple建立乙個和tuple類似的物件,而且物件擁有可訪問的屬性 可利用collections.namedtuple構建乙個簡單的類。from collections import namedtuple 定義乙個namedtuple型別use...