Note: List of Tuples vs Dict in python3 ================================================================================= 工作上的需求(偏向數據分析安餒),需要在找出關鍵字串後,再去計算字串相關數值和參考值的偏差(百分比計),最初的寫法邏輯大致如下: ```python= # define Ref. ref_1 = 201 ref_2 = 193 # define target-searched target_string=[ "string_1", "string_2" ] ... # call calculator func for s in target_string: if s == "string_1": ref = ref_1 計算func(文件讀取, s, ref) elif s == "string_2": ref = ref_2 計算func(文件讀取, s, ref) ``` 可以發現,同一個func在if-loop裡面被寫兩次,就為了套入不同的參考值 好處是直觀,容易理解 壞處是不精簡 像是上面case中,已然確定**特定字串和特定參考值**的組合,決定改用`dict`(字典)的手法, `ref_map`是一個dictionry(字典),`string_1`就是一個key,輸入/讀取它就會得到`ref_1`: ```python= ref_map = { "string_1": ref_1, "string_2": ref_2 } ... ... if s in ref_map: func(...) ``` 然則思考一會,前面已經有定義一組陣列(list): ```python= target_string=[ "string_1", "string_2" ] ``` 那直接用不就好了?但陣列不能直接當成字典使用,畢竟實現手法不相同 所以這邊要把list跟**元組**(tuple,中文又譯作多元組、順序組)並用, 所謂的**元組**,是另一種**有序列表**,跟list的差異在初始化之後就無法變動 (和list相對,tuple是靜態),沒有彈性,但相對安全。 概念上,tuple就是帶有順序的數列,比方如下: ```cpp= a = (1, 2, 3, 4) a[0] = 1 a[1] = 2 ... etc ``` 一串數列,1~4 給定第0項(key)可以得到1(value);反之,給定1(value)可以得到它是第0項(key) 並用方式簡單來說,就是初始化一個list,只是list當中的成員,都是一個tuple: ```python= #這是list target_string= [ "string_1", "string_2" ] #這是tuple ref = ( 201, 193 ) # 合併 list_of_tuples = [ ("string_1", 201), ("string_2", 193) ] ``` Summary --------------------------------------------------------------------------------- * 1. 定義與語法差異 | 類型 | 範例寫法 | |----------------|---------------------------| | **List of Tuples** | `pairs = [("A", 1), ("B", 2)]` | | **Dict (ref_map)** | `ref_map = {"A": 1, "B": 2}` | * 2. 遍歷方式 ```python= ## list of tuples for key, value in pairs: print(key, value) ## dict for key, value in ref_map.items(): print(key, value) ``` * 3. 存取單一值 ```python= ## List of Tuples ## 因為tuples允許重複key值,所以要找出value必須根據key for k, v in pairs: if k == "A": print(v) ## Dict print(ref_map["A"]) ``` :::info tuple:不可變、可 hash、可用作 dict key、適合代表「固定格式」的資料 list:可變、可增刪改、適合儲存一群相同或類似的東西 list of tuples:可當作簡單資料表(key-value list)、可迭代處理成 dict 或傳入函式 ::: Result --------------------------------------------------------------------------------- 最終成品如下: ```python= # define target-searched & value Ref. ## ("string", value_Ref.) target_string=[ ("string_1", 201), ("string_2", 193) ] ... # call calculator func for s, ref in target_string: 計算func(文件讀取, s, ref) ``` Ref. --------------------------------------------------------------------------------- [Python字典(dictionary)基礎與16種操作](https://selflearningsuccess.com/python-dictionary/) [Python 初學第九講 — 字典](https://medium.com/ccclub/ccclub-python-for-beginners-tutorial-533b8d8d96f3) [元組-wiki](https://zh.wikipedia.org/zh-tw/%E5%85%83%E7%BB%84) [Create a List of Tuples in Python](https://www.geeksforgeeks.org/python-create-a-list-of-tuples/) [使用list和tuple](https://liaoxuefeng.com/books/python/basic/list-tuple/index.html) [list跟tuple的操作手法](https://blog.csdn.net/m0_61885578/article/details/125074798)