python學習筆記(一)元組tuple

來源:互聯網
上載者:User

標籤:改變   rac   erro   sort   逗號   建立   對象   list   表示   

元組由簡單的對象組構成,元組與列表相似,但是元組不能在原處修改。元組位置有序的對象集合,元組通過位移來訪問。

為什麼有了列表還要元組?元組的不變性提供了某種完整性,可以確保元組在程式中不被另一個引用修改,元組類似於其他語言中的常數。

元組用圓括弧表示,對象用逗號分隔。

>>> T = (1,2,3,4,5) #建立元組>>> T[0],T[2:3] #索引;分區  下標從0開始,有起始位置的包前不包後(1, (3,))>>> T[0],T[2:5](1, (3, 4, 5))
>>> T =(‘c‘,‘a‘,‘b‘,‘d‘)>>> sorted(T) #兩種排序方法,sort()和sorted()[‘a‘, ‘b‘, ‘c‘, ‘d‘] #排序以後變成列表>>> T(‘c‘, ‘a‘, ‘b‘, ‘d‘)>>> T.sort() #不能直接對元組使用sort,因為元組不可變Traceback (most recent call last): File "<pyshell#7>", line 1, in <module> T.sort()AttributeError: ‘tuple‘ object has no attribute ‘sort‘>>> tmp = list()>>> tmp = sorted(T)>>> tmp[‘a‘, ‘b‘, ‘c‘, ‘d‘]>>> T = (1,2,3,4,5,6,2,3,2,5,6,1) #索引與計數>>> T.index(2) #第一個2出現的位置1>>> T.index(2,2) #第二個2出現的位置6>>> T.count(2) #總共2出現的次數3

 

元組不可改變,但是元組內部嵌套的列表可以改變。

>>> T=(1,[2,3],4)>>> T[1]=‘ok‘Traceback (most recent call last):  File "<pyshell#17>", line 1, in <module>    T[1]=‘ok‘TypeError: ‘tuple‘ object does not support item assignment>>> T[1][0]=‘ok‘>>> T(1, [‘ok‘, 3], 4)

 

python學習筆記(一)元組tuple

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.