【问题标题】:How does TCL compare the lists? [duplicate]TCL 是如何比较榜单的? [复制]
【发布时间】:2020-05-14 09:02:32
【问题描述】:

我有以下列表:

list1 = "a b c"
list2 = "a b c d e f"

我正在使用以下命令来检查 list1 中是否存在 list2 的任何元素。 TCL如何比较这两个榜单?下面的 foreach 循环使用的索引值是多少?是 3 (list1) 还是 6 (list2)?

    foreach list_1 $list1 list_2 $list2  {
        if {$list1 == $list2} {
             set FAIL 1
             break
           } else {
             set FAIL 0
                 break
           }
            }

谢谢。

【问题讨论】:

  • 您的代码可以简化为set FAIL [expr {$list1 == $list2}],但它并没有按照您说的做...
  • 使用来自 tcllib 的 struct::set 是我的选择

标签: tcl


【解决方案1】:

如果list1中存在list2的任何元素,我认为你想设置FAIL,所以你可以这样做:

set FAIL 0
foreach list_2 $list2  {
    if {$list_2 in $list1} {
        set FAIL 1
        break
    }
}

【讨论】:

  • 不错。 in operator 被低估了。
  • 在某些情况下,最好将list2 转换为字典(的键)并使用dict exists,因为inlist2 的大小是线性的。这样做有相当多的开销,但可以渐进地更快。
【解决方案2】:

当像你这样循环多个列表时,这些将是每次迭代的循环变量的值:

iteration  list_1  list_2
        1    a       a
        2    b       b
        3    c       c
        4    ""      d
        5    ""      e
        6    ""      f

【讨论】:

    【解决方案3】:
     proc listComp {LIST1 LIST2} {
         set diff {}
         foreach i $LIST2 {
    
             if {[lsearch -exact $LIST1 $i]==-1} {
                 lappend diff $i
             }
         }
         return $diff
     }
    
    
    set LIST1 " a b c "
    set LIST2 " a b c d e f "
    puts " LIST1 = \{$LIST1\}\n LIST2 = \{$LIST2\}\n  The element \{[listComp $LIST1 $LIST2]\} of LIST2  does'nt exist in LIST1  "
    
    
                ## Heading ##Result
      LIST1 = { a b c }
      LIST2 = { a b c d e f }
      The element {d e f} of LIST2  does'nt exist in LIST1 
    

    访问https://wiki.tcl-lang.org/page/listcomp+-Compare+the+Contents+of+two+Lists

    【讨论】:

      猜你喜欢
      • 2017-06-06
      • 1970-01-01
      • 1970-01-01
      • 2019-03-19
      • 2020-04-15
      • 1970-01-01
      • 2019-11-07
      • 2020-04-10
      • 2013-02-21
      相关资源
      最近更新 更多