2009-09-08 86 views

回答

22

更新: Mathematica版本10引入了Association數據結構(tutorial)。


有許多可能性。如果不需要添加或刪除表中的鍵或更改關聯值,最簡單的方法是使用左側的鍵和右側的值構造一個規則列表手邊,並使用Dispatch就可以了。

如果您確實需要更改表中的條目,則可以使用符號的DownValues作爲散列表。這將支持散列表通常使用的所有操作。下面是這樣做的最直接的方法:

(* Set some values in your table.*) 
In[1]:= table[a] = foo; table[b] = bar; table[c] = baz; 

(* Test whether some keys are present. *) 
In[2]:= {ValueQ[table[a]], ValueQ[table[d]]} 
Out[2]:= {True, False} 

(* Get a list of all keys and values, as delayed rules. *) 
In[3]:= DownValues[table] 
Out[3]:= {HoldPattern[table[a]] :> foo, HoldPattern[table[b]] :> bar, 
HoldPattern[table[c]] :> baz} 

(* Remove a key from your table. *) 
In[4]:= Unset[table[b]]; ValueQ[table[b]] 
Out[4]:= False 
6

我會說你可以得到最相似的結構開箱即用sparse arrays

+0

此答案值得多個選票。在我看來,使用開箱即用的結構比構建自己的結構幾乎總是更好。但是'Pillsy'也給出了很好的答案。 – Shredderroy 2013-10-13 19:27:12

3

我做了Dictionary.m模塊,其中包含:

DictHasKey = Function[ 
    { 
     dict, 
     key 
    }, 
    ValueQ[dict[key]] 
] 

DictAddKey = Function[ 
    { 
     dict, 
     key, 
     value 
    }, 
    If[ 
     DictHasKey[dict,key], 
     Print["Warning, Dictionary already has key " <> ToString[key]] 
    ]; 
    dict[key] = value; 
] 

DictKeys = Function[ 
    { 
     dict 
    }, 
    res = {}; 
    ForEach[DownValues[dict], Function[{dictKeyDescr}, 
     res = Append[res, ((dictKeyDescr[[1]]) /. dict -> neverUsedSymbolWhatever)[[1, 1]]]; 
    ]]; 
    res 
] 

DictValues = Function[ 
    { 
     dict 
    }, 
    res = {}; 
    ForEach[DownValues[dict], Function[{dictKeyDescr}, 
     res = Append[res, dictKeyDescr[[2]]]; 
    ]]; 
    res 
] 

DictKeyValuePairs = Function[ 
    { 
     dict 
    }, 
    res = {}; 
    ForEach[DownValues[dict], Function[{dictKeyDescr}, 
     res = Append[res, {((dictKeyDescr[[1]]) /. dict -> neverUsedSymbolWhatever)[[1, 1]], dictKeyDescr[[2]]}]; 
    ]]; 
    res 
] 

ForEach = Function[ 
    { 
     list, 
     func 
    }, 
    len = Length[list]; 
    For[i = 1, i <= len, i++, 
     func[ 
      list[[i]] 
     ]; 
    ]; 
] 
+0

忘記: 的ForEach =函數[ { 列表, FUNC }, LEN =長度[表] 對於[i = 1,i <= len,i ++, func [list [[i]]]; ]; ] – Fiard 2011-11-30 16:40:38

+1

你可以編輯你的答案來包含它。 – 2011-11-30 16:58:39

3

數學10引入了協會,<| k -> v |>

<|a -> x, b -> y, c -> z|> 
%[b] 
y 

這基本上是對一系列規則的包裝: 轉換一個協會的規則清單:

Association[{a -> x, b -> y, c -> z}] 
<|a -> x, b -> y, c -> z|> 

將關聯轉換爲規則列表:

Normal[<|a -> x, b -> y, c -> z|>] 
{a -> x, b -> y, c -> z} 
相關問題