Python 基礎資料類型之tuplu

來源:互聯網
上載者:User

標籤:erro   list   位置   元素   after   type   不同   次數   組合   

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

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

1、元組的定義
tuple1 = ("hello", "world", 100, 200)tuple2 = ()  # 定義空元祖tuple3 = tuple()  # 定義空元祖print type(tuple1), type(tuple2), type(tuple3)#運行結果:<type ‘tuple‘> <type ‘tuple‘> <type ‘tuple‘>
 2、訪問元組
tup1 = ("hello", "world", 100, 200);tup2 = (1, 2, 3, 4, 5, 6, 7 );print "tup1[0]: ", tup1[0]print "tup2[1:5]: ", tup2[1:5]#運行結果tup1[0]:  hellotup2[1:5]:  (2, 3, 4, 5)
3、修改/刪除元組

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

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

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

tup = ("hello", "world", 100, 200);#del = tup[2] # 該操作是不合法的del tup;print "After deleting tup : "print tup;#運行結果:After deleting tup :     print tup;NameError: name ‘tup‘ is not defined
4、元組常用方法

list.index(obj) #從列表中找出某個值第一個匹配項的索引位置

list.count(obj) #統計某個元素在列表中出現的次數

5、元組的內建函數

cmp(tuple1, tuple2) #比較兩個元組元素。

len(tuple) #計算元組元素個數。

max(tuple) #返回元組中元素最大值。

min(tuple) #返回元組中元素最小值。

tuple(seq) #將列錶轉換為元組。

 

Python 基礎資料類型之tuplu

聯繫我們

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