-1

我们可以通过 foreach 循环提取 TCL 列表的每个第 n 个元素。但是是否有单行通用 TCL cmd 可以解决问题?像带有“-stride”选项的 lindex 之类的东西。

4

2 回答 2

4

如果您有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

文档: listlmap (用于 Tcl 8.5)lmaplrepeatlreplaceset

于 2018-01-27T08:51:21.653 回答
2

不,但你可以写一个像这样的过程:

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
于 2018-01-26T22:46:34.720 回答