關聯陣列英文associative array / dictionary)係一種抽象資料型別,用嚟將每件數據都掕個獨特嘅名俾佢。

概論 編輯

一對名-值對(key-value pair)會將每件數據都掕個獨特嘅名俾佢。想像一本字典,會紀錄咗一大拃(名),當中每隻字都會掕住段字表示佢嘅意思(值)[1][2]

舉個具體例子,想像以下嘅 Python ,建立一個關聯陣列嚟將羅馬數字轉換做

my_dict = {'I': 1, 'V': 5, 'X': 10} # 創建一個關聯陣列,I 對應 1,V 對應 5,X 對應 10(詳情睇羅馬數字嘅嘢)。

print(my_dict['I']) # 呢行碼會 output「1」呢個整數,因為 my_dict 講咗 'I' 對應 1。

print(my_dict['V']) # 呢行碼會 output「5」呢個整數,因為 my_dict 講咗 'V' 對應 5。

print(my_dict['X']) # 呢行碼會 output「10」呢個整數,因為 my_dict 講咗 'X' 對應 10。

一個關聯陣列入面啲名-值對可以完全唔使用任何數,例如:

my_dict = {'First': 'Python', 'Second': 'Java', 'Third': 'C++'}

print(my_dict['First']) # 呢行碼會 output「Python」,因為 my_dict 講咗 'First' 對應 'Python'。

關聯陣列喺編程上好使好用-可以攞嚟指定「呢隻呢隻值嘅數據,通通轉換成嗰隻嗰隻值」噉嘅資訊[1]

睇埋 編輯

編輯

  1. 1.0 1.1 Collins, Graham; Syme, Donald (1995). "A theory of finite maps". Higher Order Logic Theorem Proving and Its Applications. Lecture Notes in Computer Science. 971: 122-137.
  2. Andersson, Arne (1989). "Optimal Bounds on the Dictionary Problem". Proc. Symposium on Optimal Algorithms. Lecture Notes in Computer Science. Springer Verlag. 401: 106-114.