levi.kim
levi.kim

Reputation: 3

Tcl split list elements in the list

I am trying to split some list elements in the list.

I want to make lists from:

beforelist: {{aa, bb, cc, dd, ee;} {ff, gg, hh, ii, jj;}}

to:

afterlist: {aa bb cc dd ee ff gg hh ii jj}

I tried to deal with them by using split command, but beforelist has some tricky point: comma, semicolon.

Upvotes: 0

Views: 565

Answers (3)

glenn jackman
glenn jackman

Reputation: 247210

If we remove the punctuation, we're left with 2 lists that can be concatenated

set afterlist [concat {*}[string map {, "" ; ""} $beforelist]]

Upvotes: 1

mrcalvin
mrcalvin

Reputation: 3434

This is not necessarily a problem to be tackled using lists. Keep it a string manipulation:

% set beforeList {{aa, bb, cc, dd, ee;} {ff, gg, hh, ii, jj;}}
{aa, bb, cc, dd, ee;} {ff, gg, hh, ii, jj;}
% string map {\{ "" \} "" \; "" , ""} $beforeList
aa bb cc dd ee ff gg hh ii jj

Upvotes: 0

Shawn
Shawn

Reputation: 52589

A couple of ways:

#!/usr/bin/env tclsh

set beforelist {{aa, bb, cc, dd, ee;} {ff, gg, hh, ii, jj;}}

# Iterate over each element of each list in beforelist and remove
# trailing commas and semicolons before appending to afterlist
set afterlist {}
foreach sublist $beforelist {
    foreach elem $sublist {
        lappend afterlist [regsub {[,;]$} $elem ""]
    }
}
puts "{$afterlist}"

# Remove all commas and semicolons at the end of a word followed by space
# or close brace, then append sublists to afterlist.
set afterlist {}
foreach sublist [regsub -all {\M[,;](?=[ \}])} $beforelist ""] {
    lappend afterlist {*}$sublist
}
puts "{$afterlist}"

Upvotes: 0

Related Questions