Python入門(五) tuple

來源:互聯網
上載者:User

標籤:

    在前面有提高過元組tuple是屬於Sequence中的一種,tuple的元素是使用小括弧()括起來:

tup1 = (1, ‘hello‘, ‘a‘, ‘b‘, ‘c‘, 2.01)print(tup1)#使用for迴圈依次列印tuple中的每一個元素for v in tup1:    print(v)    #使用下標訪問每一個元素for i in range(len(tup1)):    print(tup1[i])>>>1helloabc2.01

    tuple的建立非常簡單,只需要把元素用單括弧()括起來即可,元素之間用逗號分隔開。

    tuple中可以存放任意類型的元素,即除了上面代碼示範的整數、浮點數、字串,還可以是tuple, list等這些類型。

tup2 = (tup1, ‘tup2‘)#print(tup2)for v in tup2:    print(v)    >>>(1, ‘hello‘, ‘a‘, ‘b‘, ‘c‘, 2.01)tup2

    tuple最大的特點是:建立之後,不能對元素進行修改(包括刪除),修改則會直接報錯。

tup2[1] = ‘abc‘Traceback (most recent call last):  File "<pyshell#18>", line 1, in <module>    tup2[1] = ‘abc‘TypeError: ‘tuple‘ object does not support item assignment

    tuple元素的訪問,上面已經展示了通過下標去訪問,其實還可以進行截取,得到一個子tuple

print(tup1[1:])>>> (‘hello‘, ‘a‘, ‘b‘, ‘c‘, 2.01)print(tup1[1:-1:2])>>> (‘hello‘, ‘b‘)

    tuple的串連,可以把兩個tuple進行“+”,將兩個tuple串連為一個新的tuple

tup3=(‘abc‘,) #定義只有一個元素的tuple,需要在後面加上‘,‘print(tup1 + tup3)>>> (1, ‘hello‘, ‘a‘, ‘b‘, ‘c‘, 2.01, ‘abc‘)

    擷取tuple元素的個數: 

print(len(tup1))

    把list轉變為tuple:

list1 = [‘a‘, ‘b‘, ‘c‘]tuple(list1)>>> (‘a‘, ‘b‘, ‘c‘)


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.