【发布时间】: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]}" -
哈!两个非常相似的答案……
标签: escaping tcl special-characters output-formatting