17

我想使用像 HashTable 这样的结构。Wolfram Mathematica中是否有类似的结构?

4

5 回答 5

22

更新: Mathematica 10 版引入了Association数据结构(教程)。


有多种可能性。如果您不需要从表中添加或删除键或更改它们的关联值,最简单的可能性是构建一个规则列表,其中键在左侧,值在右侧-手边,并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
于 2009-09-08T14:24:22.087 回答
8

我想说你可以开箱即用的最相似的结构是sparse arrays

于 2009-09-08T04:49:25.650 回答
5

我同意 Pillsy 的观点,但也请参阅这个答案:

Mathematica 减值 Lhs

它包括一个方便的函数,用于获取哈希表的键。

于 2009-09-09T02:04:04.717 回答
4

我制作了 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]]
        ]; 
    ]; 
]
于 2011-11-30T16:34:48.587 回答
4

Mathematica 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}
于 2016-01-22T15:38:40.270 回答