Split a list of numbers into smaller list based on a range in TCL

痞子三分冷 提交于 2020-01-16 11:58:08

问题


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.

For eg: set xlist {1 2 3 4 5 ...50 51 52 ... 100 ... 101 102}

split lists: {1 ... 50} { 51 .. 100} {101 102}

result: sum(1:50)/50; sum(51:100)/50; sum(101:102)/2


回答1:


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}

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)
}}]

(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.)



来源:https://stackoverflow.com/questions/52066995/split-a-list-of-numbers-into-smaller-list-based-on-a-range-in-tcl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!