【发布时间】:2010-11-26 09:27:24
【问题描述】:
我想使用像 HashTable 这样的结构。 Wolfram Mathematica中是否有类似的结构?
【问题讨论】:
标签: data-structures wolfram-mathematica hashtable
我想使用像 HashTable 这样的结构。 Wolfram Mathematica中是否有类似的结构?
【问题讨论】:
标签: data-structures wolfram-mathematica hashtable
更新: 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
【讨论】:
我想说你可以开箱即用最相似的结构是sparse arrays。
【讨论】:
Pillsy也给出了很好的回答。
【讨论】:
我制作了 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]]
];
];
]
【讨论】:
Mathematica 10 引入了 Association,<| 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}
【讨论】: