Home > Enterprise >  tcl split list by n character
tcl split list by n character

Time:07-25

I have a list like below.

{2 1 0 2 2 0 2 3 0 2 4 0}

I would like to add comma between each 3 characters with using TCL.

{2 1 0,2 2 0,2 3 0,2 4 0}

I am looking for your help. Regards

CodePudding user response:

One way:

Append n elements at a time from your list to a string using a loop, but first append a comma if it's not the first time through.

#!/usr/bin/env tclsh

proc insert_commas {n lst} {
    set res ""
    set len [llength $lst]
    for {set i 0} {$i < $len} {incr i $n} {
        if {$i > 0} {
            append res ,
        }
        append res [lrange $lst $i [expr {$i   $n - 1}]]
    }
    return $res;
}

set lst {2 1 0 2 2 0 2 3 0 2 4 0}
puts [insert_commas 3 $lst] ;# 2 1 0,2 2 0,2 3 0,2 4 0

CodePudding user response:

If it is always definitely three elements, it is easy to use lmap and join:

set theList {2 1 0 2 2 0 2 3 0 2 4 0}
set joined [join [lmap {a b c} $theList {list $a $b $c}] ","]
  • Related