2013-10-02 89 views
0

我有一個返回單個元素或元素列表的過程。我試圖將所有返回的元素連接到一個列表中。將tcl列表連成一個列表

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$tempChildListchildList它形成像下面

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

列出的清單,但我想連接的childListtempChildList,使我最終的結果將是

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

我想使用concat命令,但問題是它不會在我的上面的用例中連接像{g {j i}}這樣的嵌套列表。

回答

2

在你的情況,我建議不平整的表,而是被其建設過程中更加小心。特別是,扁平化在列表中包含複合詞時會出現問題(當您進行花式演示時會導致事情發生嚴重錯誤,等等)。通過更加小心,知道什麼樣的結果你從::myproc得到(並假設這是一個簡單的列表),你就可以製作一個簡單的拼接列表很容易:

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

請注意,如果你熱衷從::myproc返回一個單一的項目,這個返回它:

return [list $theItem] 

但如果$theItem是一個簡單的詞(例如,某種ID),你可以逃脫不小心。

0

下面是一些可能的工作:

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 

注意當我們在步驟2中設置newlst時,結果幾乎是我們想要的。現在,只需重複步驟2,直到lstnewlst相等 - 那時候我們知道我們已經完全平坦化了列表。

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 

希望這有助於。

2

如果你可以導入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 
0

而不是給lappend childList $tempChildList,您可以使用

set childlist "$childlist $tempChildList"

if {[llength $tempChildList] > 0} { 
    set childlist "$childlist $tempChildList" 
}