Mathematica:用于替换符合条件的列表中的值的惯用法?

Lar*_*ien 4 conditional wolfram-mathematica list

我想将epsilon下面的绝对值截断为0,例如,

Truncate[{-3, -2, -1, 0, 1, 2, 3}, 1.5] -> {-3, -2, 0, 0, 0, 2, 3}
Run Code Online (Sandbox Code Playgroud)

我想我可以使用Scan []和If []来编写一个函数,但是在Mathematica中是否有更惯用的"单行"方式?

Ram*_*nka 6

许多选项都有效:

Map[If[Abs[#] < 1.5, 0, #] &, {-3, -2, -1, 0, 1, 2, 3}]
Run Code Online (Sandbox Code Playgroud)

或等效的:

If[Abs[#] < 1.5, 0, #] & /@ {-3, -2, -1, 0, 1, 2, 3}
Run Code Online (Sandbox Code Playgroud)

或者,如果您愿意:

ReplaceAll[{-3, -2, -1, 0, 1, 2, 3}, (x_ /; Abs[x] < 1.5) -> 0]
Run Code Online (Sandbox Code Playgroud)

这相当于:

{-3, -2, -1, 0, 1, 2, 3} /. (x_ /; Abs[x] < 1.5) -> 0
Run Code Online (Sandbox Code Playgroud)

要么

ReplaceAll[{-3, -2, -1, 0, 1, 2, 3}, (x_?(Abs[#] < 1.5 &)) -> 0]
Run Code Online (Sandbox Code Playgroud)

这相当于:

{-3, -2, -1, 0, 1, 2, 3} /. (x_?(Abs[#] < 1.5 &)) -> 0
Run Code Online (Sandbox Code Playgroud)


dre*_*ves 5

内置函数Chop几乎就是您正在寻找的内容(它在列表中起作用,如您的示例中所示).一个潜在的惊喜是它不会切断(截断)整数,只有浮点数.因此,为了让您的示例按预期工作,首先使用以下N函数将列表转换为浮点数:

Chop[N@{-3, -2, -1, 0, 1, 2, 3}, 1.5] -> {-3., -2., 0, 0, 0, 2., 3.}
Run Code Online (Sandbox Code Playgroud)

正如Ramashalanka所说,为了更普遍地做这类事,我建议:

If[Abs[#]<1.5&, 0, #]& /@ {-3, -2, -1, 0, 1, 2, 3}
Run Code Online (Sandbox Code Playgroud)

即,在列表上映射的lambda函数.