TCL从列表中删除一个元素

27

如何从TCL列表中删除一个元素,比如:

  1. 索引为4的元素
  2. 值为"aa"的元素

我已经使用谷歌搜索了,并没有找到任何内置函数可以实现。

7个回答

53
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(例如),如果是,则要删除该子列表。我应该如何做?附言:问题在于[lindex $list]返回的是值而不是引用。 - Narek
6
@Narek 请更新您的问题以询问您想要的内容,因为drysdam回答了您所问的问题。 - Trey Jackson
请将[lreplace $idx $idx]更改为[lreplace $mylist $idx $idx]。 - Narek
2
一个小细节;最后一项的结果不应该是 a 而应该是 a c - Andrew Barber

17

另一种删除元素的方法是将其筛选出来。这种Tcl 8.5技术与其他提到的lsearch&lreplace方法不同,因为它会从列表中删除所有给定的元素。

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

它不能搜索嵌套列表。这是因为Tcl不会过于深入了解您的数据结构而导致的。(不过,您可以使用-index选项通过比较子列表的特定元素来告诉它进行搜索。)


4
假设您想替换元素“b”:
% set L {a b c d}
a b c d

您需要将第一个元素1和最后一个元素1替换为空:

% lreplace $L 1 1
a c d

2

regsub 也可以用于从列表中删除一个值。

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

regsub b $mylist "" mylist

puts $mylist
  a  c
llength $mylist
  2

1
刚刚完成了别人已经做好的事情。
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

1
你也可以尝试这样做:

set i 0
set myl [list a b c d e f]

foreach el $myl {
   if {$el in {a b e f}} {
      set myl [lreplace $myl $i $i]
   } else {
      incr i
   }
}
set myl

0

有两种简单的方法。

# index
set mylist "a c b"
set mylist [lreplace $mylist 2 2]
puts $mylist 
a b
    
# value
set idx [lsearch $mylist "b"]
set mylist [lreplace $mylist $idx $idx]
puts $mylist
a

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接