如何检查TCL中是否存在列表元素?
假设我有一个 TCL 列表,并且我已将一些元素附加到我的列表中。现在我想检查是否附加了 6 个或 7 个元素。
为了检查列表元素是否存在于索引指定的位置,我使用了:
if { [info exists [lindex $myList 6]] } {
#if I am here then I have appended 7 elems, otherwise it should be at least 6
}
但是接缝这不起作用。我该怎么做呢?适当地?可以检查 if { [lindex $myList 6]] eq "" }
Say I have a TCL list, and I have append some elements to my list. Now I want to check if I have appended 6 or 7 elements.
In order to check if list element exists in the place specified by an index I have used:
if { [info exists [lindex $myList 6]] } {
#if I am here then I have appended 7 elems, otherwise it should be at least 6
}
But seams this does not work. How I should do that? properly? It is OK to check if { [lindex $myList 6]] eq "" }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我发现这个问题是因为我想检查列表是否包含特定项目,而不仅仅是检查列表的长度。
要查看列表中是否存在某个元素,请使用
lsearch
函数:lsearch
函数返回第一个找到的元素的索引,如果未找到给定元素,则返回-1
。通过-exact
、-glob
(默认)或-regexp
选项,可以指定模式搜索的类型。I found this question because I wanted to check if a list contains a specific item, rather than just checking the list's length.
To see if an element exists within a list, use the
lsearch
function:The
lsearch
function returns the index of the first found element or-1
if the given element wasn't found. Through the-exact
,-glob
(which is the default) or-regexp
options, the type of pattern search can be specified.为什么不使用
llength
来检查列表的长度:当然,如果你想检查特定索引处的元素,那么使用
lindex
来检索那个元素并检查它。例如if {[lindex $myList 6] == "something"}
您使用
info contains
的代码无法正常工作,因为info contains
命令检查变量是否存在。因此,您基本上是在检查是否存在名称等于[lindex $myList 6]
返回的值的变量。Why don't you use
llength
to check the length of your list:Of course, if you want to check the element at a specific index, then then use
lindex
to retrieve that element and check that. e.g.if {[lindex $myList 6] == "something"}
Your code using the
info exists
is not working, because theinfo exists
command checks if a variable exists. So you are basically checking if there is a variable whose name equals the value returned by[lindex $myList 6]
.检查 TCL 列表中是否存在的另一种方法是简单地使用“in”,例如:
它稍微干净/更具可读性!
Another way to check for existence in a list in TCL is to simply use 'in', for instance:
It's slightly cleaner/more readable!