【问题标题】:Check existence of a key in an array with multiple keys in Tcl在 Tcl 中检查具有多个键的数组中是否存在键
【发布时间】:2022-01-16 03:43:58
【问题描述】:

有没有办法在具有多个键的数组中检查键是否存在?即……

    set test_arr(n1_temp,x_cell) 3

#如您所见,test_arr 包含两个名为n1_temp 和x_cell 的键,现在我想知道是否可以检查一个名为n1_temp 的键的存在

    if {[info exists test_arr(n1_temp)] } { ## not working 
    }

请帮忙。

-问候, 希哈

【问题讨论】:

    标签: arraylist multidimensional-array tcl


    【解决方案1】:

    如您所见,test_arr 包含两个名为 n1_temp 和 x_cell 的键

    不,它有一个名为n1_temp,x_cell的键。

    改用dict,它支持实际的多维结构:

    dict set test_dict n1_temp x_cell 3
    if {[dict exists $test_dict n1_temp]} {
        # ...
    }
    

    【讨论】:

      【解决方案2】:

      您的数组有一个元素,名为n1_temp,x_cell,名称中带有逗号。

      您可以通过测试array names test_arr n1_temp,* 的结果列表的长度来检查名称的第一部分是否有任何带有n1_temp 的元素(这是一个全局匹配)。请注意,这在实践中是一项昂贵的操作,因为它必须对数组中的所有元素进行线性扫描。

      if {[llength [array names test_arr n1_temp,*]]} {
          puts "There's an n1_temp,* element present"
      }
      

      【讨论】:

      • FWIW,当您为任何语言的任何应用程序设计数据设置时,您需要考虑的一件事是您想就数据提出什么样的问题。如果获取与特定标签相关的所有内容预计是一项常见操作,那么优化数据的结构以使其易于执行就很重要。
      猜你喜欢
      • 1970-01-01
      • 2016-08-07
      • 2012-10-21
      • 2011-07-05
      • 1970-01-01
      • 2017-09-05
      • 2016-08-28
      • 2013-10-25
      • 2020-10-25
      相关资源
      最近更新 更多