根据列表中的元素更改嵌套列表中的值 [英] Changing values in nested lists according to elements in the list

查看:38
本文介绍了根据列表中的元素更改嵌套列表中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 mathematica 中有一个值对列表,例如 List= {{3,1},{5,4}}.

I have a list of pairs of values in mathematica, for example List= {{3,1},{5,4}}.

如果第二个元素未达到阈值,我如何更改第一个元素 (3 & 5).例如,如果第二部分低于 2,那么我希望第一部分归零.因此该列表 = {{0,1},{5,4}}.不幸的是,其中一些列表非常长,因此无法手动执行此操作.

How do I change the first element (3 & 5) if the second element does not reach a threshold. For example, if the second parts are below 2 then i wish the first parts to go to zero. so that list then = {{0,1},{5,4}}. Some of these lists are extremely long so manually doing it is not an option, unfortunately.

推荐答案

概念上,一般的方式是使用 地图.在您的情况下,代码将是

Conceptually, the general way is to use Map. In your case, the code would be

In[13]:= lst = {{3, 1}, {5, 4}}

Out[13]= {{3, 1}, {5, 4}}

In[14]:= thr = 2

Out[14]= 2

In[15]:= Map[{If[#[[2]] < thr, 0, #[[1]]], #[[2]]} &, lst]

Out[15]= {{0, 1}, {5, 4}}

这里的 # 符号代表函数参数.您可以在此处阅读有关纯函数的更多信息.双方括号代表 Part 提取.您可以通过使用 Apply 在级别 1 上,缩写为 @@@:

The # symbol here stands for the function argument. You can read more on pure functions here. Double square brackets stand for the Part extraction. You can make it a bit more concise by using Apply on level 1, which is abbreviated by @@@:

In[27]:= {If[#2 < thr, 0, #], #2} & @@@ lst

Out[27]= {{0, 1}, {5, 4}}

但是请注意,对于大型数字列表,第一种方法要快几倍.一个更快,但更模糊的方法是这样的:

Note however that the first method is several times faster for large numerical lists. An even faster, but somewhat more obscure method is this:

In[29]:= Transpose[{#[[All, 1]]*UnitStep[#[[All, 2]] - thr], #[[All, 2]]}] &[lst]

Out[29]= {{0, 1}, {5, 4}}

它更快,因为它使用了非常优化的向量化操作,可以同时应用于所有子列表.最后,如果你想要极致的性能,这个程序编译成 C 版本会快 2 倍:

It is faster because it uses very optimized vectorized operations which apply to all sub-lists at once. Finally, if you want the ultimate performance, this procedural compiled to C version will be another factor of 2 faster:

fn = Compile[{{lst, _Integer, 2}, {threshold, _Real}},
  Module[{copy = lst, i = 1},
    For[i = 1, i <= Length[lst], i++,
      If[copy[[i, 2]] < threshold, copy[[i, 1]] = 0]];
    copy], CompilationTarget -> "C", RuntimeOptions -> "Speed"] 

你把它当作

In[32]:= fn[lst, 2] 

Out[32]= {{0, 1}, {5, 4}}

对于最后一个,您需要在您的机器上安装 C 编译器.

For this last one, you need a C compiler installed on your machine.

这篇关于根据列表中的元素更改嵌套列表中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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