tcl中lsearch中的-end索引

时间:2012-08-10 07:50:13

标签: tcl

lsearch命令有-start index作为选项之一

  

-start index 从位置 index 开始搜索列表。如果 index 的值为 end ,则它引用列表中的最后一个元素,并且   结束 - 整数是指列表中的最后一个元素减去指定的元素   整数偏移量。

我想将-end-start一起使用。怎么做到呢? 可以通过丢弃-end返回列表中大于或等于lsearch索引的索引来完成。但还有更好的方法吗?

1 个答案:

答案 0 :(得分:4)

我很想在你的情况下使用lrange生成一个被搜索列表的副本,而不会返回你不希望返回的元素。

lsearch [lrange $theList $start $end] $searchTerm

-start选项的真正目的是允许跳过以前找到的匹配项,而现在我们拥有-all选项(使lsearch返回所有的列表,它可以匹配搜索词的位置)。它有点像这样使用:

for {set idx -1} {[set idx [lsearch -start [incr idx] $list $term]] >= 0} {} {
    # Process the match index...
    puts "found $term at $idx"
}

现在你写了:

foreach idx [lsearch -all $list $term] {
    puts "found $term at $idx"
}