元祖的創建
元祖創建很簡單,只需要在括號中添加元素,并使用逗號隔開即可。
>>> temp=(1)>>> temp1>>> type(temp)<class 'int'>
>>> temp2=1,2,3,4,5>>> temp2(1, 2, 3, 4, 5)>>> type(temp2)<class 'tuple'>
>>> temp=[]>>> type(temp)<class 'list'>
>>> temp=()>>> type(temp)<class 'tuple'>
>>> temp=(1,)>>> temp(1,)>>> type(temp)<class 'tuple'>
對元組各個元素進行命名
1,通過對元組索引值的命名
2,通過標準庫中的collections.nametuple
替代內置touple
通過對元組索引值的命名
好比在c中的defined詳細見代碼
name,gender,age = range(3)student = ("ruioniao","man","19")student["name"]student["age"]student["gender"]#輸出#"ruoniao"#19#man
使用標準庫中collections.nametuple
代替內置的tuple
s這個變量名可以直接通過屬性方式訪問
Student是namedtuple的名稱,后面的列表是其元素創建時還可以
s= Student(name="ruoniao",age="19",sex="man") #輸出Student(name='ruoniao', age='19', sex='man')
可以通過‘點'像類訪問屬性那樣進行訪問
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對武林站長站的支持。
新聞熱點
疑難解答