gpt4 book ai didi

list - 数学 : Idiomatic way to replace values in a list that match a condition?

转载 作者:行者123 更新时间:2023-12-04 22:17:04 25 4
gpt4 key购买 nike

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

Truncate[{-3, -2, -1, 0, 1, 2, 3}, 1.5] -> {-3, -2, 0, 0, 0, 2, 3}

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

最佳答案

很多选项都有效:

Map[If[Abs[#] < 1.5, 0, #] &, {-3, -2, -1, 0, 1, 2, 3}]

或等价物:
If[Abs[#] < 1.5, 0, #] & /@ {-3, -2, -1, 0, 1, 2, 3}

或者,如果您愿意:
ReplaceAll[{-3, -2, -1, 0, 1, 2, 3}, (x_ /; Abs[x] < 1.5) -> 0]

这相当于:
{-3, -2, -1, 0, 1, 2, 3} /. (x_ /; Abs[x] < 1.5) -> 0

或者
ReplaceAll[{-3, -2, -1, 0, 1, 2, 3}, (x_?(Abs[#] < 1.5 &)) -> 0]

这相当于:
{-3, -2, -1, 0, 1, 2, 3} /. (x_?(Abs[#] < 1.5 &)) -> 0

关于list - 数学 : Idiomatic way to replace values in a list that match a condition?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2241716/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com