将 Mathematica 值列表转换为布尔列表
首先,对混乱的标题表示歉意。
我想要做的是将 {1, 4, 9}
转换为:
{True, False, False, True, False, False, False, False, True}
也就是说,只有第一个列表中的索引才会具有值 True
,其余的将为错误
。
我感觉有一些非常简单的解决方案,但我对 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 ->;正确,4 ->确实,9 ->正确}
。但我不知道如何做到这一点...
编辑2:明白了。
ReplacePart[Table[False, {x, Max[first]}], Table[x -> True, {x, first}]]
我仍然很想看到您的解决方案!这对我来说似乎是一个丑陋的黑客......:)
First of all, sorry for the confused title.
What I want to do is to convert {1, 4, 9}
to:
{True, False, False, True, False, False, False, False, True}
That is, only the indexes from the first list will have value True
, the rest will be False
.
I sense there is some really simple solution, but I am quite new to both Mathematica and functional programming. I could do it iteratively, in a loop, but there has to be something that works with the list as a whole. Right? :)
Thanks for your help.
EDIT: to show that I tried to do something before I asked, here's my progress so far:
first={1,4,9}
ReplacePart[Table[False, {x, Max[first]}], {1} -> True]
(* gives {True, False, False, False, False, False, False, False, False} *)
Unfortunately, it doesn't work with {1,4,9} -> True
, but would work with {1 -> True, 4 -> True, 9 -> True}
. But I don't know how to get to that...
EDIT 2: got it.
ReplacePart[Table[False, {x, Max[first]}], Table[x -> True, {x, first}]]
I'd still love to see your solutions! This one seems like an ugly hack to me ... :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是一个简单的方法:
这是将上述解决方案编写为一个方便的函数:
用法:
Here's a simple approach:
Here's the above solution written as a convenient function:
Usage:
我将使用 SparseArray 来执行此操作。在我看来,它非常容易理解,而且也很高效,特别是当索引为 True 的比例较低时。
或者使用
Transpose
(粘贴到 Mathematica 中时看起来更好):如果必须将输出转换为普通数组,则可以使用
Normal
,但是大多数操作不需要这样做。另外,为了简洁而牺牲实用性:
I would use
SparseArray
for this operation. In my opinion it is very easy to understand, and it is also efficient, especially when a low percentage of indices are True.Alternatively with
Transpose
(which looks better when pasted into Mathematica):You can use
Normal
if you must convert the output to a normal array, but most operations will not require that.Also, sacrificing practicality for terseness:
实际上,我自己会使用 Yoda 的答案,但这里有一种替代方法:
或者这个:
两者都有跳过 Yoda 的
ConstantArray
初始化步骤的优点。Actually, I would have used Yoda's answer myself, but here's an alternative:
Or this one:
Both have the advantage that they skip Yoda's
ConstantArray
initialization step.