我有一个排序的数字列表,我试图根据 50 的范围将列表拆分为更小的列表,并在 TCL 中找到平均值。
例如:set xlist {1 2 3 4 5 ...50 51 52 ... 100 ... 101 102}
拆分列表:{1 ... 50} { 51 .. 100} {101 102}
结果:sum(1:50)/50; sum(51:100)/50; sum(101:102)/2
该lrange命令是您在这里需要的核心。结合一个for循环,这会给你你所追求的分裂。
proc splitByCount {list count} {
set result {}
for {set i 0} {$i < [llength $list]} {incr i $count} {
lappend result [lrange $list $i [expr {$i + $count - 1}]]
}
return $result
}
以交互方式测试(使用较小的输入数据集)对我来说看起来不错:
% splitByCount {a b c d e f g h i j k l} 5
{a b c d e} {f g h i j} {k l}
您想要的其余部分是lmap和tcl::mathop::+(+表达式运算符的命令形式)的简单应用。
set sums [lmap sublist [splitByCount $inputList 50] {
expr {[tcl::mathop::+ {*}$sublist] / double([llength $sublist])}
}]
我们可以通过定义一个自定义函数来使它稍微整洁一些:
proc tcl::mathfunc::average {list} {expr {
[tcl::mathop::+ 0.0 {*}$list] / [llength $list]
}}
set sums [lmap sublist [splitByCount $inputList 50] {expr {
average($sublist)
}}]
(expr在这两种情况下,我已将命令移至上一行,以便我可以假装过程的主体 /lmap是表达式而不是脚本。)