Extract every n-th element from TCL list [closed]

我是研究僧i 提交于 2019-12-13 08:19:34

问题


we can extract every n-th element of a TCL list by foreach loop. But is there a single line generic TCL cmd that will do the trick? Something like lindex with a '-stride' option.


回答1:


If you have lmap (Tcl 8.5 version in the links below) you can do this:

lmap [lrepeat $n a] $list {set a}

Example:

set list {a b c d e f g h i j k l}
set n 2
lmap [lrepeat $n a] $list {set a}
# => b d f h j l

But your comment seems to indicate that you really want the n+1 th value. In that case:

lmap [lreplace [lrepeat $n b] 0 0 a] $list {set a}
# => a c e g i k

Documentation: list, lmap (for Tcl 8.5), lmap, lrepeat, lreplace, set




回答2:


No, but you can do write a proc like:

proc each_nth {list n} {
    set result [list]
    set varlist [lreplace [lrepeat $n -] end end nth]
    while {[llength $list] >= $n} {
        set list [lassign $list {*}$varlist]
        lappend result $nth
    }
    return $result
}

and then:

each_nth {a b c d e f g h i j k l} 3    ;# => c f i l
each_nth {a b c d e f g h i j k l} 4    ;# => d h l
each_nth {a b c d e f g h i j k l} 5    ;# => e j


来源:https://stackoverflow.com/questions/48470087/extract-every-n-th-element-from-tcl-list

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