Q 語言 - 字典



字典是列表的擴充套件,為建立表格提供了基礎。在數學術語中,字典建立了

“域 → 值域”

或者一般(簡短)建立

“鍵 → 值”

元素之間的關係。

字典是鍵值對的有序集合,大致相當於雜湊表。字典是由域列表和值域列表透過位置對應關係之間顯式 I/O 關聯定義的對映。字典的建立使用“xkey”原語(!)。

                  ListOfDomain ! ListOfRange

最基本的字典將一個簡單列表對映到一個簡單列表。

輸入 (I) 輸出 (O)
`姓名 `約翰
`年齡 36
`性別 “男”
體重 60.3
q)d:`Name`Age`Sex`Weight!(`John;36;"M";60.3)   / Create a dictionary d

q)d

Name   | `John
Age    | 36
Sex    | "M"
Weight | 60.3

q)count d             / To get the number of rows in a dictionary.
4

q)key d               / The function key returns the domain
`Name`Age`Sex`Weight

q)value d             / The function value returns the range.

`John
36

"M"
60.3

q)cols d             / The function cols also returns the domain.
`Name`Age`Sex`Weight

查詢

查詢與輸入值對應的字典輸出值稱為查詢輸入。

q)d[`Name]       / Accessing the value of domain `Name
`John

q)d[`Name`Sex]   / extended item-wise to a simple list of keys
`John
"M"

使用動詞 @ 進行查詢

q)d1:`one`two`three!9 18 27

q)d1[`two]
18

q)d1@`two
18

字典操作

修改和更新

與列表一樣,可以透過索引賦值修改字典的專案。

d:`Name`Age`Sex`Weight! (`John;36;"M";60.3)
                                  / A dictionary d
                                  
q)d[`Age]:35                      / Assigning new value to key Age

q)d 
                              / New value assigned to key Age in d
Name   | `John
Age    | 35
Sex    | "M"
Weight | 60.3

可以透過索引賦值擴充套件字典。

q)d[`Height]:"182 Ft"

q)d

Name   | `John
Age    | 35
Sex    | "M"
Weight | 60.3
Height | "182 Ft"

使用查詢 (?) 進行反向查詢

查詢 (?) 運算子用於透過將一系列元素對映到其域元素來執行反向查詢。

q)d2:`x`y`z!99 88 77

q)d2?77
`z

如果列表的元素不唯一,則查詢返回從域列表對映到它的第一個專案。

刪除條目

要從字典中刪除條目,可以使用刪除 (_) 函式。(_) 的左運算元是字典,右運算元是鍵值。

q)d2:`x`y`z!99 88 77

q)d2 _`z

x| 99
y| 88

如果第一個運算元是變數,則 _ 的左側需要空格。

q)`x`y _ d2           / Deleting multiple entries

z| 77

列字典

列字典是建立表格的基礎。考慮以下示例 -

q)scores: `name`id!(`John`Jenny`Jonathan;9 18 27)
                              / Dictionary scores
                              
q)scores[`name]               / The values for the name column are
`John`Jenny`Jonathan

q)scores.name                 / Retrieving the values for a column in a
                              / column dictionary using dot notation.
`John`Jenny`Jonathan

q)scores[`name][1]            / Values in row 1 of the name column
`Jenny

q)scores[`id][2]              / Values in row 2 of the id column is
27

翻轉字典

翻轉列字典的淨效果只是反轉索引的順序。這在邏輯上等效於轉置行和列。

列字典上的翻轉

字典的轉置是透過應用一元翻轉運算子獲得的。看看下面的例子 -

q)scores

name  | John Jenny Jonathan
id    | 9   18   27

q)flip scores

  name     id
---------------
  John     9
  Jenny    18
 Jonathan  27

翻轉後的列字典的翻轉

如果轉置字典兩次,則獲得原始字典,

q)scores ~ flip flip scores
1b
廣告