[7] 進階資料型別 part2 - Tuple


Posted by bessyhuang on 2023-06-03

Tuple 序對;元组

為何需要 Tuple?

簡介

  • 由一連串資料所組成、有順序且不可改變內容(immutable)的序列。
  • ( ) 小括號 標示,裡面的資料以逗號 , 隔開。
  • tuple 中可以包含不同型別的元素。
      test1 = (1, "Taipei", 2, "Tokyo")
    
  • 若 tuple 的元素相同但順序不同,表示不同 tuple。

      test1 = (1, "Taipei", 2, "Tokyo")
      test2 = (2, 1, "Taipei", "Tokyo")
    
      print(test1 == test2)
      #False
    

建立序對

  • 空序對

      # 方法一:使用 Python 內建的 tuple() 函式建立串列
      tuple1 = tuple()
    
      # 方法二
      tuple1 = ()
    
  • 包含數值或文字的序對

      tuple2 = tuple([1, 2, 3])
      tuple3 = ('A', 'B', 'C', 'D')
    
      print(tuple2, type(tuple2))
      # ('A', 'B', 'C', 'D') <class 'tuple'>
    
  • 從 range 建立序對

      # 方法一
      tuple4 = tuple(range(5))
    
      # 方法二:串列解析法 (List comprehension)
      tuple4 = tuple([i for i in range(5)])
    
      # ERROR: 'tuple' object has no attribute 'append'
      tuple5 = ()
      for i in range(5):
          tuple5.append(i)
    

內建函式

💡 原則上,適用於 list 且 不會涉及變更元素 的運算子均適用於 tuple。

  • 適用
    • len(T)max(T)min(T)sum(T)
  • 不適用
    • random 模組的 shuffle(L):將 L 中的元素隨機重排。(涉及變更元素的順序)

運算子

  • 適用

    • +*

        print((1, 'abc', '我') + ('Taipei', 2))
        # (1, 'abc', '我', 'Taipei', 2)
      
        print((1, 'a') * 3)
        # (1, 'a', 1, 'a', 1, 'a')
      
    • 比較運算子: > < >= <= == !=
    • in not in 運算子
        print("ab" in (2, "abc", "ba"))
        # False
      
    • Index 與 Slicing
        💡 預設:   T[ 0 : len(T) : 1] == T[ : ] == T
        => T[start : end : step]
      

序對處理方法

💡 符號表示之說明
     - x  單一的元素
     - T  序對 (tuple)
     - i  索引值
  • 適用

    • tuple.index(x)tuple.count(x)
        T = (10, 20, 30, 1, 2, 10)
        print(T.index(10))        # 傳回元素 10 第一次出現的索引
        # 0
        print(T.count(10))        # 傳回元素10出現的次數
        # 2
      
    • sorted(T)

        💡 T.sort() 對原始 tuple 的元素排序,未創建新的 tuple。
           => 出現 Error!
      
        💡 sorted(T) 對由 tuple 新產生的 list 元素排序,不改變原始 tuple。
      
        T = (1, 0, 3, 4, 2, -1, 1.5, 5)
        print(T.sort())
        # ERROR: 'tuple' object has no attribute 'sort'
        print(T)
        # (1, 0, 3, 4, 2, -1, 1.5, 5)
      
        T1 = (1, 0, 3, 4, 2, -1, 1.5, 5)
        print(sorted(T1))
        # [-1, 0, 1, 1.5, 2, 3, 4, 5]
        print(T1)
        # (1, 0, 3, 4, 2, -1, 1.5, 5)
      
    • del:刪除 變數本身

        💡 del 只可用來刪除變數,而不可刪除 tuple 裡的元素。
      
        T = (-1, 1.5, 0, 1, 2, 3, 4, 5)
        del T
      
  • 不適用
    • list.append(x)list.extend(L)list.insert(i, x)list.remove(x)list.pop([i])
    • list.sort(reverse=False)list.reverse()list.copy()list.clear()
    • del:用來從 list 中 刪除 指定索引 的元素。

References

  1. Python List VS Array VS Tuple

#Python #Tuple







Related Posts

NoSQL, Transaction, ACID and Lock

NoSQL, Transaction, ACID and Lock

PM2、Nginx & Reverse Proxy Server

PM2、Nginx & Reverse Proxy Server

CH3. 初探頭等函式 : 定義與引數

CH3. 初探頭等函式 : 定義與引數


Comments