问题
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