根据TCL中的范围将数字列表拆分为较小的列表 [英] Split a list of numbers into smaller list based on a range in TCL
问题描述
我有一个排序的数字列表,我试图根据50的范围将列表分成较小的列表,并在TCL中找到平均值.
I have a sorted list of numbers and I am trying to split the list into smaller lists based on range of 50 and find the average in 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
循环,可以为您带来所需的分割效果.
The lrange
command is the core of what you need here. Combined with a for
loop, that'll give you the splitting that you're after.
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
}
交互式测试(使用较小的输入数据集)对我来说不错:
Testing that interactively (with a smaller input dataset) looks good to me:
% 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::+
(+
表达式运算符的命令形式)的简单应用了.
The rest of what you want is a trivial application of lmap
and tcl::mathop::+
(the command form of the +
expression operator).
set sums [lmap sublist [splitByCount $inputList 50] {
expr {[tcl::mathop::+ {*}$sublist] / double([llength $sublist])}
}]
我们可以通过定义一个自定义函数来使其更加整洁:
We can make that slightly neater by defining a custom function:
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
的主体是表达式而不是脚本.)
(I've moved the expr
command to the previous line in the two cases so that I can pretend that the body of the procedure/lmap
is an expression instead of a script.)
这篇关于根据TCL中的范围将数字列表拆分为较小的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!