2009-09-08 29 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} 
相关问题