将Mathematica值列表转换为布尔列表

时间:2011-11-05 21:22:33

标签: list wolfram-mathematica boolean

首先,抱歉这个混乱的标题。

我想要做的是将{1, 4, 9}转换为:

{True, False, False, True, False, False, False, False, True}

也就是说,只有第一个列表中的索引具有值True,其余的将为False

我觉得有一些非常简单的解决方案,但我对Mathematica和函数式编程都很陌生。我可以在一个循环中迭代地完成它,但必须有一些与整个列表一起工作的东西。对? :)

感谢您的帮助。


编辑:表示在我问之前我尝试过做一些事情,这是我到目前为止的进展:

first={1,4,9}
ReplacePart[Table[False, {x, Max[first]}], {1} -> True]
(* gives {True, False, False, False, False, False, False, False, False} *)

不幸的是,它不适用于{1,4,9} -> True,但适用于{1 -> True, 4 -> True, 9 -> True}。但我不知道该怎么做......


编辑2:得到了它。

ReplacePart[Table[False, {x, Max[first]}], Table[x -> True, {x, first}]]

我仍然希望看到你的解决方案!这对我来说似乎是一个丑陋的黑客...... :)

3 个答案:

答案 0 :(得分:13)

这是一个简单的方法:

first = {1, 4, 9};
list = ConstantArray[False, Max@first];
list[[first]] = True;

list
Out[1]= {True, False, False, True, False, False, False, False, True}

以上是上述解决方案,作为一个方便的功能:

Clear[convertIndices]
convertIndices[index_List] := 
 Module[{list = ConstantArray[False, Max@index]}, 
  list[[index]] = True; list]

<强>用法:

convertIndices@{1, 4, 9}
Out[2]= {True, False, False, True, False, False, False, False, True}

答案 1 :(得分:8)

我会使用SparseArray进行此操作。在我看来,这很容易理解,而且效率也很高,特别是当指数的百分比很低时。

true = {1, 4, 9};
SparseArray[(List /@ true) -> True, Automatic, False]

或者使用Transpose(粘贴到 Mathematica 时效果更好):

SparseArray[{true}\[Transpose] -> True, Automatic, False]

如果必须将输出转换为普通数组,则可以使用Normal,但大多数操作要求输出。


另外,牺牲简洁性的实用性:

#==1 & /@ SparseArray[List /@ true -> 1]

答案 2 :(得分:2)

实际上,我自己会使用尤达的答案,但这里有另一种选择:

first = {1, 4, 9};
MemberQ[first, #] & /@ Range[Max[first]]

(* ===> {True, False, False, True, False, False, False, False, True}*)

或者这个:

Or @@@ Outer[Equal, Range[Max[first]], first]


(* ===> {True, False, False, True, False, False, False, False, True}*)

两者都具有跳过Yoda的ConstantArray初始化步骤的优势。