Python tuple(元組)

veelion發表於2018-12-24

元組(tuple)跟列表(list)非常相似,二者之間的差異就是元組不可改變,list是可以改變的。

python tuple

建立元組(tuple)

跟list的中括號不同,元組用圓括號把所有項括起來,元素之間用逗號分隔:

In [15]: mytuple = ('a', 'b', 3, 8.9, [1,2])

In [16]: mytuple
Out[16]: ('a', 'b', 3, 8.9, [1, 2])

In [17]: x = ('a', )  # 只有一個元素的元組
In [18]: y = ()  # 空元組

元組(tuple)的索引(index)

元組的索引機制跟列表完全一樣,看下面的示例:

In [22]: mytuple[0]
Out[22]: 'a'

In [23]: mytuple[1]
Out[23]: 'b'

In [24]: mytuple[3]
Out[24]: 8.9

同樣,元組也有負索引:

In [25]: mytuple[-1]
Out[25]: [1, 2]

In [26]: mytuple[-2]
Out[26]: 8.9

Python元組的索引可以是正索引(從頭到尾),也可以是負索引(從尾到頭),總結為下面的關係:

元組:  ('a', 'b', 'c', 'd', 'e')
         |    |    |    |    |
正索引:  0    1    2    3    4
負索引:  -5  -4   -3   -2   -1

因為元組是不可修改的,我們通過索引企圖修改元素時,就會報錯:

In [116]: x = ('a', 1, [1,2])

In [117]: x[1] = 2
--------------------------------------------
TypeError    Traceback (most recent call last)
<ipython-input-117-fe7b4192b649> in <module>
----> 1 x[1] = 2

TypeError: 'tuple' object does not support item assignment

In [118]: x[2][1] = 3  #修改的不是元組,而是list

In [119]: x
Out[119]: ('a', 1, [1, 3])

In [121]: x[2] = ['a', 'b']  # 此處企圖修改第三個元素,報錯!
--------------------------------
TypeError    Traceback (most recent call last)
<ipython-input-121-339ad61923f7> in <module>
----> 1 x[2] = ['a', 'b']

TypeError: 'tuple' object does not support item assignment

但是,我們修改元組中的list時卻成功了。元組x的前兩個元素’a’, 1都是不可變的,而第三個元素是list,這個list是可以改變的,但不能把第三個元素賦值為其它list(上面示例中最後一個操作)或其它任何型別的資料。

python 元組

元組(tuple)的切片(slicing)

元組的切片跟列表也是一樣的

In [27]: mytuple[1:3]
Out[27]: ['b', 3]

In [28]: mytuple[:3]
Out[28]: ['a', 'b', 3]

In [29]: mytuple[1:]
Out[29]: ['b', 3, 8.9, [1, 2]]

In [30]: mytuple[:]
Out[30]: ['a', 'b', 3, 8.9, [1, 2]]

上面例子中,切片範圍的起止索引可以是缺失的,左邊缺失就是從頭(0)開始,右邊缺失就是後面的全部。

元組(tuple)運算子

元組的運算子跟列表也一樣:

運算子 含義 表示式 結果
+ 合併在一起 ('a', 'b', 'c') + (1, 2, 3) ('a', 'b', 'c', 1, 2, 3)
* 重複 ('a',) * 3 ('a', 'a', 'a')
in 是否為元素 'a' in ('a', 'b') True

從頭到尾遍歷(迭代)一個tuple的語法是:for x in the-tuple

for x in (1, 2, 3):
    print(x)

刪除元組(tuple)

(1)刪除整個元組

In [35]: mytuple = ['a', 'b', 3, 8.9, [1,2]]

In [36]: del mytuple

In [37]: mytuple
---------------------------------------------------------------------------
NameError    Traceback (most recent call last)
<ipython-input-37-1dc2d082cc20> in <module>
----> 1 list_a

NameError: name 'list_a' is not defined

由於元組是不可改變的,我們就不能像列表那樣,使用del來刪除元組的元素。

In [127]: x = ('a', 1, [1,2])

In [128]: del x[0]
--------------------------------
TypeError     Traceback (most recent call last)
<ipython-input-128-ec9e6e663ef5> in <module>
----> 1 del x[0]

TypeError: 'tuple' object doesn't support item deletion

元組相關的內建函式

(1)len()
計算元組的長度,即計算元組元素的個數)

In [55]: len([1,2,3])
Out[55]: 3

(2)max()
返回元組元素中的最大值,元組元素必須是同一型別且可比較,比如都是數字型的,或都是字串,如果型別不統一就會報錯:

In [57]: max(('a', 'b', 'c'))
Out[57]: 'c'

In [58]: max((1,2,'a'))
---------------------------------------------------------------------------
TypeError   Traceback (most recent call last)
<ipython-input-58-d6e404f692f3> in <module>
----> 1 max((1,2,'a'))

TypeError: '>' not supported between instances of 'str' and 'int'

(3)min()
返回元組元素中的最小值。元素型別要求跟max()一樣。

In [59]: min((1,2,3))
Out[59]: 1

In [60]: min(('a', 'b', 'c'))
Out[60]: 'a'

In [61]: min((1,2,'a'))
---------------------------------------------------------------------------
TypeError    Traceback (most recent call last)
<ipython-input-61-c2d30ec5fffc> in <module>
----> 1 min((1,2,'a'))

TypeError: '<' not supported between instances of 'str' and 'int'

(4)sum()
計算元組所有元素的和,其元素型別必須是數值型的(整數、浮點數)

In [63]: sum((1,2,3))
Out[63]: 6

In [64]: sum((1.2, 3.2, 4.3))
Out[64]: 8.7

In [65]: sum(('a', 'b', 'c'))
---------------------------------------------------------------------------
TypeError   Traceback (most recent call last)
<ipython-input-65-f2e6eb2051e3> in <module>
----> 1 sum(('a', 'b', 'c'))

TypeError: unsupported operand type(s) for +: 'int' and 'str'

(5)sorted()
返回一個排序的列表,但並不改變原元組。

In [66]: sorted((3, 9, 0, 5))
Out[66]: [0, 3, 5, 9]

In [68]: sorted(('python', 'yuanrenxue', 'good'))
Out[68]: ['good', 'python', 'yuanrenxue']

(6)tuple()
生成一個空元組,或把其它型別資料轉換成元組。

In [69]: tuple()
Out[69]: ()

In [70]: tuple('python')
Out[70]: ('p', 'y', 't', 'h', 'o', 'n')

(7)any()
只要元組中有一個元素是True就返回True。

In [72]: any((0, '', '3'))
Out[72]: True

(8)all()
只有元組所有元素為True才返回True。

In [73]: all((0, '', '3'))
Out[73]: False

In [74]: all((3, 'a', True))
Out[74]: True

元組(tuple)的內建方法

由於元組的不可改變,它的方法也比列表少了很多,只有兩個:

index(v) 返回第一個值為v的元素的索引;
count(v) 返回值為v的元素的個數。

In [138]: x = (1,3,2,6,2,4)

In [139]: x.index(2)
Out[139]: 2

In [140]: x.count(2)
Out[140]: 2

元組的拆包(Unpacking)

Python中如果要初始化多個變數,可以用下面的方式:

In [141]: a,b,c,d = 1,2,3,4

In [142]: a,b,c,d
Out[142]: (1, 2, 3, 4)

以上程式碼給a,b,c,d分別賦值1,2,3,4,這時候a是1,b是2,c是3,d是4

還有更絕的拆包方法,那就是用星號*來吸收多餘的元素:

In [146]: x = (1,2,3,4,5)

In [147]: a, *b = x # x有5個元素,左邊變數只有兩個,多餘的都被帶*的b吸收了

In [148]: a, b
Out[148]: (1, [2, 3, 4, 5])

In [149]: a, *b, c = x #多虧帶*的b

In [150]: a,b,c
Out[150]: (1, [2, 3, 4], 5)

In [151]: *a, b, c = x #多虧帶*的a

In [152]: a,b,c
Out[152]: ([1, 2, 3], 4, 5)

In [153]: a,b,c = x #沒有帶*的,x的5個元素無法匹配3個變數
---------------------
ValueError     Traceback (most recent call last)
<ipython-input-153-58e3b82a91cc> in <module>
----> 1 a,b,c = x

ValueError: too many values to unpack (expected 3)

總結

元組跟列表非常相似,前者不能被修改,後者隨便改。

練習

  1. 熟悉對元組的各種操作。
  2. 比較列表和元組的相似與不同。

猿人學banner宣傳圖

我的公眾號:猿人學 Python 上會分享更多心得體會,敬請關注。

***版權申明:若沒有特殊說明,文章皆是猿人學 yuanrenxue.com 原創,沒有猿人學授權,請勿以任何形式轉載。***

相關文章