最简单的:
Map2 = # @@@ Partition[#2, 2, 1] &;
或者,可能使用较少的内存,但运行速度有点慢:
Map2[f_, lst_] := Developer`PartitionMap[f @@ # &, lst, 2, 1]
另外,请注意Differences 和Accumulate,它们是相关的。
其他方式:
Inner[#, Most@#2, Rest@#2, List] &
请注意,List 可能是一个不同的函数。
MapThread[#, {Most@#2, Rest@#2}] &
Most@MapThread[#, {#2, RotateLeft@#2}] &
Rest@MapThread[#, {RotateRight@#2, #2}] &
Table[# @@ #2[[i ;; i + 1]], {i, Length@#2 - 1}] &
现在,时间安排。我会使用Timo's timeAvg。
f1 = # @@@ Partition[#2, 2, 1] &;
f2[f_, lst_] := Developer`PartitionMap[f @@ # &, lst, 2, 1]
f3 = Inner[#, Most@#2, Rest@#2, List] &;
f4 = MapThread[#, {Most@#2, Rest@#2}] &;
f5 = Most@MapThread[#, {#2, RotateLeft@#2}] &;
f6 = Table[# @@ #2[[i ;; i + 1]], {i, Length@#2 - 1}] &;
timings =
Table[
list = RandomReal[99, 10^i];
func = Plus;
timeAvg[#[func, list]] & /@ {f1, f2, f3, f4, f5, f6},
{i, 6}
];
TableForm[timings,
TableHeadings -> {10^Range@6, {"f1", "f2", "f3", "f4", "f5", "f6"}}]
ListLogPlot[timings\[Transpose], Joined -> True]
表格左侧的数字是每次运行的实数列表的长度。
请注意,图表是对数的。
以下是处理最长列表 (1,000,000) 时使用的内存字节数:
完成上述计时后,我发现我可以通过消除 Apply (@@) 使 f6 更快。它现在显然是较长列表中最快的。我不会将它添加到上表中,因为它已经足够宽了,但这里是函数及其时间:
f7 = Table[#2[[i]] ~#~ #2[[i + 1]], {i, Length@#2 - 1}] &;