【问题标题】:Add an opening brace to the beginning of a list in tcl在 tcl 列表的开头添加一个左大括号
【发布时间】:2021-06-13 17:46:47
【问题描述】:

我试图在 tcl 中找到两组的笛卡尔积。我的逻辑已经准备好了,但是我需要美化输出并在列表的开头放置一个左大括号。我可以使用 append 命令在末尾追加,但是在列表开头这样做时会抛出错误。以下是代码:

set a {0 1}
set b {1 2 3}
set s {}
append s "\{"                                              ### this is where the problem is
for {set i 0} { $i < 2 } {incr i} {
         for {set j $i} { $j < 2 } {incr j} {
                  set x "([lindex $a $i],[lindex $b $j])"
                  lappend s "$x,"
                  
         }
         if {$j == 2} {
                  set x "([lindex $a $i],[lindex $b $j])"
                  lappend s "$x"
               }
      }
      append s }
      puts $s

现在使用

append s "\{" 

给予

unmatched open brace in list

另一方面,使用

append s "\\{"

给出以下输出:

\{ (0,1), (0,2), (0,3) (1,2), (1,3)}

有没有办法可以删除第一个斜杠以及左大括号和第一个括号之间的空格?

【问题讨论】:

  • 您正在尝试构建一个字符串,而不是一个列表。所以最好使用append之类的字符串命令,而不是lappend之类的列表命令。这样可以避免在打印结果时发生魔术引用。
  • 或者,构建列表并将其放在最后的大括号中:puts "{[join $s]}"
  • 您可能对此感兴趣:wiki.tcl-lang.org/page/Cartesian+product
  • 哈!两个非常相似的答案……

标签: escaping tcl special-characters output-formatting


【解决方案1】:

使用列表的优点是您可以轻松地将其用逗号连接起来,因此您不必像现在这样对最后一个元素进行特殊处理。在加入列表后,最容易将整个东西放在大括号中:

set a {0 1}
set b {1 2 3}
set s {}
for {set i 0} {$i < 2} {incr i} {
    for {set j $i} {$j < 3} {incr j} {
        set x "([lindex $a $i],[lindex $b $j])"
        lappend s $x
    }
}
puts "{[join $s ", "]}"

【讨论】:

    【解决方案2】:

    最好将输出构建为列表,然后将其转换为字符串:

    set a {0 1}
    set b {1 2 3}
    
    # The list of cells to appear in the output
    set cells {}
    # [foreach] is nicer than [for]/[lindex]
    foreach i $a {
        foreach j $b {
            # Format a single cell
            lappend cells "($i,$j)"
        }
    }
    # Produce the result string with [string cat] and [join]
    set result [string cat "{" [join $cells ", "] "}"]
    puts $result
    

    【讨论】:

    • 上面写着:unknown or ambiguous subcommand "cat": must be bytelength, compare, equal, first, index, is, last, length, map, match, range, repeat, replace, reverse, tolower, totitle, toupper, trim, trimleft, trimright, wordend, or wordstart while executing "string cat "{" [join $cells ", "] "}"" invoked from within "set result [string cat "{" [join $cells ", "] "}"]" (file "tt.tcl" line 14) 我是否遗漏了任何软件包或者是版本问题?
    • 我考虑在我的回答中使用foreach,直到我注意到内部循环应该从元素 $i 而不是 0 开始。然后我决定更接近原始代码。跨度>
    • @SaranshChoudhary 你用的是什么版本的 tcl?
    • 对于string cat,您需要 Tcl 8.6.3 或更高版本。 (我不完全确定 .3。它是在 8.6 之上的某个补丁级别中添加的)
    • 查看发行说明,发现string cat最早出现在Tcl 8.6.2中。
    猜你喜欢
    • 2018-08-22
    • 2012-11-15
    • 2018-11-07
    • 2013-10-01
    • 1970-01-01
    • 2021-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多