在 tcl 中的列表的开头添加一个左大括号

问题描述

我试图在 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),3) (1,(1,3)}

有没有办法去掉第一个斜线和左大括号和第一个括号之间的空格?

解决方法

使用列表的优点是你可以很容易地用逗号将它连接起来,所以你不必像你正在做的那样对最后一个元素进行特殊处理。在加入列表之后,将整个事情放在大括号中最容易在最后完成:

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

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

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...