问题描述
我试图在 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