Python基礎教程筆記十三:元組

來源:互聯網
上載者:User

標籤:組合   try   刪除   需要   most   span   開始   print   列表   

Python 元組

Python的元組與列表類似,不同之處在於元組的元素不能修改。

元組使用小括弧,列表使用方括弧。

元組建立很簡單,只需要在括弧中添加元素,並使用逗號隔開即可。

如下執行個體:

tup1 = (‘physics‘, ‘chemistry‘, 1997, 2000);tup2 = (1, 2, 3, 4, 5 );tup3 = "a", "b", "c", "d";

建立空元組:

tup1 = ();

元組中只包含一個元素時,需要在元素後面添加逗號:

tup1 = (50,);

元組與字串類似,下標索引從0開始,可以進行截取,組合等。

訪問元組

元組可以使用下標索引來訪問元組中的值,如下執行個體:

tup1 = (‘physics‘, ‘chemistry‘, 1997, 2000);tup2 = (1, 2, 3, 4, 5, 6, 7 );print "tup1[0]: ", tup1[0]print "tup2[1:5]: ", tup2[1:5]

結果:

tup1[0]:  physicstup2[1:5]:  (2, 3, 4, 5)
修改元組

元組中的元素值是不允許修改的,但我們可以對元組進行串連組合,如下執行個體:

tup1 = (12, 34.56);tup2 = (‘abc‘, ‘xyz‘);# 以下修改元組元素操作是非法的。# tup1[0] = 100;# 建立一個新的元組tup3 = tup1 + tup2;print tup3;

結果:

(12, 34.56, ‘abc‘, ‘xyz‘)
刪除元組

元組中的元素值是不允許刪除的,但我們可以使用del語句來刪除整個元組,如下執行個體:

tup = (‘physics‘, ‘chemistry‘, 1997, 2000);print tup;del tup;print "After deleting tup : "print tup;

以上執行個體元組被刪除後,輸出變數會有異常資訊,輸出如下所示:

(‘physics‘, ‘chemistry‘, 1997, 2000)After deleting tup :Traceback (most recent call last):  File "test.py", line 9, in <module>    print tup;NameError: name ‘tup‘ is not defined

 

Python基礎教程筆記十三:元組

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.