在 Mathematica 的 MapAt 中使用 All [英] Using All in MapAt in Mathematica

查看:39
本文介绍了在 Mathematica 的 MapAt 中使用 All的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常有一个对的列表,如

I often have a list of pairs, as

data = {{0,0.0},{1,12.4},{2,14.6},{3,25.1}}

并且我想对所有第二个元素做一些事情,例如 Rescale,而不触及第一个元素.我所知道的最简洁的方法是:

and I want to do something, for instance Rescale, to all of the second elements without touching the first elements. The neatest way I know is:

Transpose[MapAt[Rescale, Transpose[data], 2]]

必须有一种方法可以做到这一点,而无需过多的 Transpose 操作.我的愿望是让这样的事情起作用:

There must be a way to do this without so much Transposeing. My wish is for something like this to work:

MapAt[Rescale, data, {All, 2}]

但我的理解是 MapAt 采用 Position-style 规范而不是 Part-style 规范.什么是正确的解决方案?

But my understanding is that MapAt takes Position-style specifications instead of Part-style specifications. What's the proper solution?

我正在寻找一种不必重复自己的解决方案,因此缺少双 Transpose 或双 [[All,2]],因为我认为重复一个信号我不是在做最简单的事情.但是,如果消除重复需要引入中间变量或命名函数或其他额外的复杂性,那么转置/取消转置解决方案可能已经正确.

I'm seeking a solution where I don't have to repeat myself, so lacking double Transpose or double [[All,2]], because I consider repetition a signal I'm not doing something the easiest way. However, if eliminating the repetition requires the introduction of intermediate variables or a named function or other additional complexity, maybe the transpose/untranspose solution is already correct.

推荐答案

使用 部分:

data = {{0, 0.0}, {1, 12.4}, {2, 14.6}, {3, 25.1}}

data[[All, 2]] = Rescale @ data[[All, 2]];

data

如果需要,请先创建一个副本.(data2 = data 然后 data2[[All, 2]] 等等)

Create a copy first if you need to. (data2 = data then data2[[All, 2]] etc.)

修改我的答案以跟上ruebenko的,这也可以变成一个函数:

Amending my answer to keep up with ruebenko's, this can be made into a function also:

partReplace[dat_, func_, spec__] :=
  Module[{a = dat},
    a[[spec]] = func @ a[[spec]];
    a
  ]

partReplace[data, Rescale, All, 2]

这是很一般的设计.

这篇关于在 Mathematica 的 MapAt 中使用 All的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆