Python 入門系列 —— 17. tuple 簡介

tuple

tuple 經常使用來將多個 item 放在一個變量中,同時tuple也是python 4個集合類型之一,其餘的三個是:List,Set,Dictionary,它們都有本身的用途和場景。python

tuple 是一個有序但不可更改的集合,用 () 來表示,以下代碼所示:git

thistuple = ("apple", "banana", "cherry")
print(thistuple)

PS E:\dream\markdown\python> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.py
('apple', 'banana', 'cherry')

tuple 項

tuple中的項是有序的,不可更改的,而且能夠重複的值,同時tuple中的項也是索引過的,也就是說你可使用相似 [0][1] 的方式對 tuple 進行訪問。github

排序

須要注意的是,之因此說 tuple 是有序的,指的是 tuple item 是按照順序定義的,而且這個順序是不可更改的。markdown

不可修改

所謂 tuple 不可修改,指的是不可對 tuple 中的item 進行變動。app

容許重複

由於 tuple 是索引化的,意味着不一樣的索引能夠具備相同的值,好比下面的代碼。函數

thistuple = ("apple", "banana", "cherry", "apple", "cherry")
print(thistuple)

PS E:\dream\markdown\python> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.py
('apple', 'banana', 'cherry', 'apple', 'cherry')

Tuple 長度

要想知道 tuple 中有多少項,可使用 len() 函數,以下代碼所示:this

thistuple = ("apple", "banana", "cherry")
print(len(thistuple))

PS E:\dream\markdown\python> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.py
3

建立單值的 tuple

要想建立一個單值 tuple,須要在 item 以後添加 , ,不然 python 不會認爲這個單值的集合爲 tuple,以下代碼所示:code

thistuple = ("apple",)
print(type(thistuple))

#NOT a tuple
thistuple = ("apple")
print(type(thistuple))

PS E:\dream\markdown\python> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.py
<class 'tuple'>
<class 'str'>

Tuple 中的數據類型

tuple中的項能夠是任意類型,好比說:string,int,boolean 等等,以下代碼所示:排序

tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)

又或者 tuple 中的 item 是混雜的,好比下面這樣。索引

tuple1 = ("abc", 34, True, 40, "male")

type()

從 python 的視角來看,tuples 就是一個 tuple class 類,以下代碼所示:

mytuple = ("apple", "banana", "cherry")
print(type(mytuple))

PS E:\dream\markdown\python> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.py
<class 'tuple'>

tuple() 構造函數

儘量的使用 tuple() 構造函數來生成一個 tuple。

thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets
print(thistuple)

PS E:\dream\markdown\python> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.py
('apple', 'banana', 'cherry')
譯文連接: https://www.w3schools.com/pyt...

更多高質量乾貨:參見個人 GitHub: python

相關文章
相關標籤/搜索