hashtable - Mathematica中的MemberQ

标签 hashtable wolfram-mathematica

我有点不知所措,如何在Mathematica中有效地执行以下操作:

a = { 1, 2, 3, 4, 5 };  (* list of integers *)
b = { 2, 4, 6, 8 };     (* another list of integers *)
filter = Table[MemberQ[b, element], {element,a}]

预期输出为:
{False, True, False, True, False}

我的列表ab很大,因此Mathematica通过b进行了数以百万计的线性搜索。我希望它通过哈希表进行更快的查找。但是似乎没有这样的结构。我能找到的最接近的是SparseArray,但是
sa = SparseArray[{1 -> True, 2 -> True}];
MemberQ[sa, 1]

False

我敢肯定,在Mathematica中,只需一行或更少的代码就可以做到这一点,我只是看不到树木之类的东西。

有英雄要营救吗?同时,我将使用C#进行此操作。

最佳答案

另一个想法是使用规则和Dispatch。当blist的长度很大时,它似乎会更快:

alist = Prime /@ Range[20000];
blist = alist + 2;

membQ = First@Timing[MemberQ[blist,#]&/@alist;]

sparse = First@Timing[
    s = SparseArray[blist -> ConstantArray[True, Length@blist], Max[alist, blist], False];
    s[[#]] & /@ alist;
]

rules = First@Timing[
    bRules = Dispatch[Append[Rule[#, True] & /@ blist, _ -> False]];
    (# /. bRules) & /@ alist;
]

fct = First@Timing[
    f[_] = False;
    (f[#] = True) & /@ blist;
    f /@ alist;
]

在我的笔记本电脑上,规则(0.06s)
编辑/比较功能和规则时间

@Karsten请随时回滚到您的原始答案

用Prime [...]生成的表

用RandomInteger [...]生成的表

关于hashtable - Mathematica中的MemberQ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3696147/

相关文章:

c++ - 使用智能指针制作哈希表?

delphi - 如何判断TBucketList的桶数

c++ - 哈希表的析构函数

wolfram-mathematica - 关于绘图过程——关于 "A problem in Mathematica 8 with function declaration"的另一个问题

c# - 多键散列或字典,值列表作为输出

c++ - 对于这个英语单词列表,什么是好的散列函数?

python - SciPy 中的二维积分

wolfram-mathematica - $mathematica 界面失败

wolfram-mathematica - Mathematica Graphics3D中的阴影

user-interface - 对话操作