05-01元組

元組

特性:

  • 元組的最大特性是不可變。
  • 不可變意味着可hash, 意味着可以做字典的key, 可以做set的元素。
  • 函數時,元組的作用更強大。

元組對象操作

針對元組對象本身做的操作

新建元組

方法1:t = tuple()
方法2:t = ()
方法3:t = (1, 2, 3) # 直接賦值
方法4:t = tuple(range(3))

刪除元組對象

需要使用del方法刪除
截至2020年5月23日,本人暫時還未發現其他的方法

In [1]: t = ()                                                                                                                                                                    

In [2]: type(t)                                                                                                                                                                   
Out[2]: tuple

In [3]: del t 

元組元素操作

元組是不可變的, 所以只有查詢方法

查詢

通過下標查詢

  • 超出範圍, 會報錯IndexError。
  • 同樣支持負數取值。
  • 不支持賦值, 元組是不可變的。
In [5]: t[0]   
Out[5]: 0

In [6]: t[4]    # 超出範圍,報錯IndexError
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-6-302761d4dd84> in <module>()
----> 1 t[4]

IndexError: tuple index out of range

In [7]: t[-1]   # 同樣支持負數取值
Out[7]: 2

In [8]: t[0] = 3   # 不支持賦值, 元組是不可變的
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-8-d7bb3c58ee7f> in <module>()
----> 1 t[0] = 3

TypeError: 'tuple' object does not support item assignment

總結:
    1、超出範圍, 會報錯IndexError。
    2、同樣支持負數取值。
    3、不支持賦值, 元組是不可變的。

tuple.index通過值查找索引

tuple.index方法和list.index方法一致,通過值查找索引
不存在的拋ValueError

In [10]: t.index(2)   # 查找2在第幾個index
Out[10]: 2

In [11]: t.index(3)   # 不存在的拋ValueError
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-11-bbaa43d3e6ff> in <module>()
----> 1 t.index(3)

ValueError: tuple.index(x): x not in tuple

總結:
    1、不存在的拋ValueError

tuple.count統計值在元組中出現的個數

tuple.count和list.count方法表現一致

In [12]: t.count(2)  
Out[12]: 1

In [13]: t.count(10)    # 統計不存在的值爲零
Out[13]: 0

總結元組特性:
元組的最大特性是不可變。
不可變意味着可hash, 意味着可以做字典的key, 可以做set的元素。
函數時,元組的作用更強大。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章