我正在尝试拆分列表中的一些列表元素。
我想从
beforelist:{{aa, bb, cc, dd, ee;} {ff, gg, hh, ii, jj;}}
:
afterlist:{aa bb cc dd ee ff gg hh ii jj}
我试图通过使用分割命令来处理它们,但是beforelist
有一些棘手的点:逗号,分号。
如果我们去掉标点符号,我们就剩下两个可以连接的列表
set afterlist [concat {*}[string map {, "" ; ""} $beforelist]]
方法:
#!/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}"
这个问题不一定要用列表来解决。保持为字符串操作:
% 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