从 TCL 列表中提取每个第 n 个元素



我们可以通过foreach循环提取TCL列表的每个n个元素。但是有没有单行通用TCL cmd可以做到这一点?类似于带有"-stride"选项的 lindex。

如果您有lmap(以下链接中的Tcl 8.5版本(,则可以执行此操作:

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

例:

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

但是您的评论似乎表明您确实想要第 n+1 个值。在这种情况下:

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

文档:列表lmap(对于Tcl 8.5(,LMAP,lrepeat,替换,设置

不,但你可以写一个过程,比如:

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
}

然后:

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

最新更新