当前位置: 动力学知识库 > 问答 > 编程问答 >

Tcl: strange behavior of string list

问题描述:

In my following code, I generate a string list in a for loop like this:

set section 5;

set value 2;

set value_range_new "";

for { set i [expr -$section-1]} {$i <= $section} {incr i} {

if {$i < [expr -$section]} {

lappend value_range_new "\<[expr [expr $i+1]*$value]";

} elseif {$i == $section} {

lappend value_range_new "\>[expr $i*$value]";

} else {

lappend value_range_new "\[[expr $i*$value]\,[expr [expr $i +1]*$value]\)";

}

}

then if I puts the list out, the result is following:

<-10 {[-10,-8)} {[-8,-6)} {[-6,-4)} {[-4,-2)} {[-2,0)} {[0,2)} {[2,4)} {[4,6)} {[6,8)} {[8,10)} >10

The confusing point is I do not understand where the {} comes from. If I define the list manually like following :

set a "\<-8 \[-8,-6\) \[-6,-4\) ";

the puts result has no {}. So what's wrong with my code, and how to remove/

网友答案:

In Tcl, you need to be aware which commands want to work with lists and which commands want to work with strings. lappend is a list command. puts takes a string. When you give puts a list, Tcl will convert the list into its string representation. That means that you'll see some extra braces and perhaps backslashes to protect list elements that have special characters (like [ and ]).

You can convert the list into a string easily with the join command.

For building strings, the format command can aid readability.

Additionally, you don't need to next expr commands, use parentheses; and brace your expressions:

set section 5;
set value 2;
set value_range_new "";
for { set i [expr {-$section-1}]} {$i <= $section} {incr i} {
  set this [expr {$i * $value}]
  set next [expr {($i + 1) * $value}]
  if {$i < -$section} {
    lappend value_range_new [format {<%d} $next]  
  } elseif {$i == $section} {
    lappend value_range_new [format {>%d} $this]
  } else {
    lappend value_range_new [format {[%d,%d)} $this $next]
  }
}
puts [join $value_range_new]

outputs

<-10 [-10,-8) [-8,-6) [-6,-4) [-4,-2) [-2,0) [0,2) [2,4) [4,6) [6,8) [8,10) >10
网友答案:

The shorter variant of algorithm. Not a single if is needed actually.

set section 5;
set value 2;
set this [expr {-$section * $value}]
set value_range_new [format {<%d} $this]  
for {set i -$section} {$i < $section} {incr i} {
  lappend value_range_new [format {[%d,%d)} $this [incr this $value]]
}
lappend value_range_new [format {>%d} $this]

puts [join $value_range_new]
分享给朋友:
您可能感兴趣的文章:
随机阅读: