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

2021-09-25 19:17:03 字數 1760 閱讀 7294

當物件資料格式固定時,用元組比列表更節省記憶體空間,

我們使用索引訪問元組元素,但是這種訪問方式會降低程式的可讀性。

舉個栗子

對於學生的資訊,我們有固定的資料格式,我們可以用元組表示,

但是在我們使用它的時候並不知道stu1[1],stu[2]具體代表什麼資訊,

這就大大降低了程式的可讀性

stu1 = ("

tom", 16, "

male")

deffun1(stu):

if stu1[1]:

pass

if stu1[2] == '

male':

pass

fun1(stu1)

那我們怎麼提高程式的可讀性呢,解決方法如下

定義一系列數值常量

name =0

age = 1*** = 2stu1 = ("

tom", 16, "

male")

deffun1(stu):

ifstu1[name]:

pass

if stu1[***] == '

male':

pass

fun1(stu1)

分析:但是這種方式比較低效,我們可以採用元組的拆包

name, age, *** = range(3)

stu1 = ("

tom", 16, "

male")

deffun1(stu):

ifstu1[name]:

pass

if stu1[***] == '

male':

pass

fun1(stu1)

分析:如果還有乙個老師的資料結構,元組的第一項是年齡,第二項是姓名,

如果在程式中有多種資料結構,還使用定義常量的方式,有些常量會衝突,

如果分開物件去定義常量,如stu_name, tea_name, stu_age, tea_age,這樣全域性變數太多

一般這種情況我們會使用列舉

列舉優點:相當於創造了乙個命名空間

from enum import

intenum

class

studentenum(intenum):

name =0

age = 1*** = 2stu1 = ("

tom", 16, "

male")

print(studentenum.name ==0) #true

print(studentenum.age == 1) #true

print(isinstance(studentenum.name, int)) #true

優點:使用元組可以節省空間

提公升程式可讀性

from collections import

namedtuple

student = namedtuple('

student

', ['

name

', '

age', '

***'

])stu1 = student("

tom", 16, "

male")

print

(isinstance(stu1, tuple)) #true

print

(stu1.name) #「tom」

print(stu1.age) #16

python 資料結構 元組 tuple

字串 變數引用str s abc s abc 元組 如果這樣寫,就會是.t 123,abc come here t 123,abc come here 上面例子中看到的變數t,並沒有報錯,也沒有 最後乙個有效 而是將物件做為乙個新的資料型別 tuple 元組 賦值給了變數t。元組是用圓括號括起來的,...

Python之資料結構 元組

元組與列表的最大區別是列表可以修改 可以讀取 可以刪除,而元組建立之後則不能修改,但是可以刪除整個元組。1 定義元組 l1 1,2,3 print l1 print type l1 執行結果 如果元組只有乙個元素,則這個元素後面必須要有 否則元素就還是其原來的型別。l1 1,2,3 print l1...

Python的資料結構 元組

zoo 大象 老虎 獅子 北極熊 print the animal number of the is len zoo print the animal of the zoo are zoo new zoo 孔雀 鱷魚 zoo print the new animal is new zoo print...