我相信还有比已经给出什么更快的方法,但首先,约书亚的Cases
方法可以通过使用/;
而不是&
进行快一点进行测试。
这是我提出解决方案(编辑:增加了对清晰的白色空间,因为双括号这里不格式化):
dat[[
Position[
dat[[All, 2]],
x_ /; x >= 100,
1, 1
][[1, 1]],
1
]]
下面是提供的各种方法计时。请注意,/.
方法只运行一次,其他运行方式则运行loops
次。因此,在第一次测试中,它比Position
方法慢100倍。此外,NestWhile
方法只返回索引,而不是实际的第一列元素。
In[]:=
dat = {Range[5000], [email protected][1*^6, 5000]} // Transpose;
lim = 300000; loops = 100;
dat /. {___, {x_, _?(# >= lim &)}, ___} :> x; // Timing
Do[ Cases[dat, {_, _?(# >= lim &)}, 1, 1][[1, 1]] , {loops}] // Timing
Do[ Cases[dat, {_, y_ /; y >= lim}, 1, 1][[1, 1]] , {loops}] // Timing
Do[ Select[dat, #[[2]] >= lim &, 1][[1, 1]] , {loops}] // Timing
Do[ NestWhile[# + 1 &, 1, dat[[#, 2]] < lim &] , {loops}] // Timing
Do[ dat[[Position[dat[[All, 2]], x_ /; x >= lim, 1, 1][[1, 1]], 1]] , {loops}] // Timing
Out[]= {0.125, Null}
Out[]= {0.438, Null}
Out[]= {0.406, Null}
Out[]= {0.469, Null}
Out[]= {0.281, Null}
Out[]= {0.125, Null}
有了更长的表(我离开了缓慢的方法):
In[]:=
dat = {Range[35000], [email protected][1*^6, 35000]} // Transpose;
lim = 300000; loops = 25;
Do[ Cases[dat, {_, _?(# >= lim &)}, 1, 1][[1, 1]] , {loops}] // Timing
Do[ Cases[dat, {_, y_ /; y >= lim}, 1, 1][[1, 1]] , {loops}] // Timing
Do[ Select[dat, #[[2]] >= lim &, 1][[1, 1]] , {loops}] // Timing
Do[ NestWhile[# + 1 &, 1, dat[[#, 2]] < lim &] , {loops}] // Timing
Do[ dat[[Position[dat[[All, 2]], x_ /; x >= lim, 1, 1][[1, 1]], 1]] , {loops}] // Timing
Out[]= {0.734, Null}
Out[]= {0.641, Null}
Out[]= {0.734, Null}
Out[]= {0.5, Null}
Out[]= {0.266, Null}
最后,协议的确认:
In[]:= SameQ[
Select[dat, #[[2]] >= lim &, 1][[1, 1]],
dat[[Position[dat[[All, 2]], x_ /; x >= lim, 1, 1][[1, 1]], 1]]
]
Out[]= True
这真的是一个数学问题吗? – 2010-11-14 21:58:05