0

我有一个返回单个元素或元素列表的过程。我正在尝试将所有返回的元素连接到一个列表中。

set childList [list];
foreach item $myList {
    lappend childList $item; 
    set tempChildList [::myproc $item];  #for different items it will return either single element or a list of elements. 
    if {[llength $tempChildList] > 0} {
        lappend childList $tempChildList;
    }
}

所以现在在我的最后一个声明中,当我lappend $tempChildList进入childList它时,它会形成一个列表列表,如下所示

{a {b c} {d e f} {g {h i}} j}

但我想连接childListandtempChildList以便我的最终结果是

{a b c d e f g h i j}

我正在考虑使用命令,但问题是它不会像我上面的用例concat那样连接嵌套列表。{g {j i}}

4

6 回答 6

3

如果你可以导入struct::list模块,你可以这样做:

% package require struct::list
1.8.1
% set oldlist {a {b c} {d e f} {g {h i}} j}
% set newlist [::struct::list flatten -full $oldlist]
a b c d e f g h i j
于 2013-10-03T05:46:44.967 回答
2

这是可能有用的东西:

proc flatten {lst} {
    while 1 {
        set newlst [concat {*}$lst]
        if {$newlst == $lst} { break }
        set lst $newlst
    }
    return $newlst
}

set lst {a {b c} {{{1 2} 3} 4} {d e f} {g {h i}} j}
puts [flatten $lst]

输出:

a b c 1 2 3 4 d e f g h i j

讨论

请看以下交互式会话:

(1) % set lst {a {b c} {d e f} {g {h i}} j}
a {b c} {d e f} {g {h i}} j

(2) % set newlst [concat {*}$lst]
a b c d e f g {h i} j

请注意,当我们newlst在步骤 2 中设置时,结果几乎就是我们想要的。现在,只需重复第 2 步,直到lstnewlst相等——这时我们知道我们已经完全展平了列表。

于 2013-10-03T00:33:30.593 回答
2

在您的情况下,我建议不要扁平化列表,而是在构建过程中更加小心。特别是,扁平化存在列表包含复合词的问题(当你做一个花哨的演示时,这可能会导致事情发生可怕的错误,以及类似的事情)。通过更加小心,知道你得到什么样的结果::myproc(并假设这是一个简单的列表),你可以很容易地生成一个简单的串联列表:

set childList [list]
foreach item $myList {
    lappend childList $item {*}[::myproc $item]
}

请注意,如果您热衷于从::myproc中退回单件商品,请使用以下方式退回:

return [list $theItem]

虽然 if$theItem是一个简单的词(例如,某种 ID),但您可以不小心就逃脱。

于 2013-10-03T08:21:14.673 回答
1

试试这个:

% set list {a {b c} {d e f} {g {h i}} j}
 {a {b c} {d e f} {g {h i}} j}
% set newlist [regsub -all "\{|\}" $list ""]
 a b c d e f g h i j

希望这可以帮助。

于 2013-10-03T05:28:15.013 回答
0

而不是给予lappend childList $tempChildList,你可以使用

set childlist "$childlist $tempChildList"

if {[llength $tempChildList] > 0} {
   set childlist "$childlist $tempChildList"
}
于 2013-10-03T09:57:45.043 回答
0

尝试:

% set str {a {b c} {d e f} {g {h i}} j}

% while {1} {if [regexp -- {\\{} $str] {set str [join $str]} else {break}}

% set str

% a b c d e f g h i j
于 2018-12-27T18:34:46.293 回答