2011-04-18 61 views
18

TE如何從TCL列表中刪除元件說:TCL從列表中刪除元件

  1. 具有索引= 4
  2. 具有值= 「AA」

我已經Google搜索並且還沒有找到任何內置功能。

回答

34
set mylist {a b c} 
puts $mylist 
a b c 

通過指數

刪除
set mylist [lreplace $mylist 2 2] 
puts $mylist 
a b 

刪除值

set idx [lsearch $mylist "b"] 
set mylist [lreplace $mylist $idx $idx] 
puts $mylist 
a 
+0

這是偉大的,但我的名單由來自子列表打電話,我想在每個子表,如果檢查第二個索引中的值爲0(例如),我想刪除該子列表。我應該怎麼做。附:問題是[lindex $ list]返回的值不是參考 – Narek 2011-04-18 11:27:54

+5

@Narek然後請更新您的問題,問問你想要什麼,B/C drysdam回答了你問的問題。 – 2011-04-18 12:20:31

+0

請將[lreplace $ idx $ idx]更改爲[lreplace $ mylist $ idx $ idx]。 – Narek 2011-05-11 05:10:14

4

比方說,你要替換元素 「B」:

% set L {a b c d} 
a b c d 

您可以通過任何更換第一器件和最後一個元素1:

% lreplace $L 1 1 
a c d 
15

另一種刪除元素的方法是將其過濾掉。這種Tcl 8.5技術不同於其他地方提到的方法,因爲它從列表中刪除給定元素的全部

set stripped [lsearch -inline -all -not -exact $inputList $elemToRemove] 

它沒有做的是通過嵌套列表進行搜索。這是Tcl沒有努力深入理解您的數據結構的結果。 (你可以告訴它通過比較雖然子列表中的具體內容進行搜索,通過-index選項。)

1

regsub也可以適用於從列表中刪除值。

set mylist {a b c} 
puts $mylist 
    a b c 

regsub b $mylist "" mylist 

puts $mylist 
    a c 
llength $mylist 
    2 
0

剛剛結束了別人怎麼做

proc _lremove {listName val {byval false}} { 
    upvar $listName list 

    if {$byval} { 
     set list [lsearch -all -inline -not $list $val] 
    } else { 
     set list [lreplace $list $val $val] 
    } 

    return $list 
} 

然後用

Inline edit, list lappend 
    set output [list 1 2 3 20] 
    _lremove output 0 
    echo $output 
    >> 2 3 20 

Set output like lreplace/lsearch 
    set output [list 1 2 3 20] 
    echo [_lremove output 0] 
    >> 2 3 20 

Remove by value 
    set output [list 1 2 3 20] 
    echo [_lremove output 3 true] 
    >> 1 2 20 

Remove by value with wildcar 
    set output [list 1 2 3 20] 
    echo [_lremove output "2*" true] 
    >> 1 3