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.
Asked
Active
Viewed 1,869 times
2 Answers
4
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

Peter Lewerin
- 13,140
- 1
- 24
- 27
-
Gave this 'accepted answer' as it does not involve a proc or loop and can be given as one-liner. – Gert Gottschalk Feb 02 '18 at 18:36
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

glenn jackman
- 238,783
- 38
- 220
- 352
-
-
1In my particular case n=2 so I came up with foreach { x y } $l {lappend z $x} But a more generic case for n is appreciated. – Gert Gottschalk Jan 27 '18 at 02:22