list 如何检查TCL中是否存在列表元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5617624/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 01:37:45  来源:igfitidea点击:

How to check if list element exists in TCL?

listtclexists

提问by Narek

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.

假设我有一个 TCL 列表,并且我已将一些元素附加到我的列表中。现在我想检查我是否附加了 6 或 7 个元素。

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 "" }

但是接缝这不起作用。我该怎么做?适当地?可以检查{ [lindex $myList 6]] eq "" }

回答by überjesus

Why don't you use llengthto check the length of your list:

你为什么不用llength来检查你的列表的长度:

if {[llength $myList] == 6} {
    # do something
}

Of course, if you want to check the element at a specific index, then then use lindexto retrieve that element and check that. e.g. if {[lindex $myList 6] == "something"}

当然,如果您想检查特定索引处的元素,则使用lindex来检索该元素并进行检查。例如if {[lindex $myList 6] == "something"}

Your code using the info existsis not working, because the info existscommand 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].

您使用 的代码info exists不起作用,因为该info exists命令会检查变量是否存在。因此,您基本上是在检查是否存在名称等于[lindex $myList 6].

回答by FriendFX

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 lsearchfunction:

要查看列表中是否存在元素,请使用以下lsearch函数:

if {[lsearch -exact $myList 4] >= 0} {
    puts "Found 4 in myList!"
}

The lsearchfunction returns the index of the first found element or -1if the given element wasn't found. Through the -exact, -glob(which is the default) or -regexpoptions, the type of pattern search can be specified.

lsearch函数返回第一个找到的元素的索引,或者-1如果未找到给定的元素。通过-exact, -glob(这是默认值)或-regexp选项,可以指定模式搜索的类型。

回答by Andrew Rooney

Another way to check for existence in a list in TCL is to simply use 'in', for instance:

在 TCL 中检查列表中是否存在的另一种方法是简单地使用“in”,例如:

if {"4" in $myList} {
    puts "Found 4 in my list"
}

It's slightly cleaner/more readable!

它更干净/更具可读性!