3

我写了一个 Tcl 代码,它给了我如下的输出。我非常接近我需要的东西。代码:

for { set row 0 } { $row < 3 } {incr row } {
set row[expr {$row + 1}] [lindex $sub_list $row]
puts "row[expr {$row + 1}] [lindex $sub_list $row]"
set pattern_number [llength [lindex $sub_list $row]]
puts "pattern_number = $pattern number"
set pattern_index [lindex $sub_list $row]

    for {set p 0} { $p < $pattern_number} {incr p} {
      set pattern[expr {$p + 1}] [lindex $pattern_index $p]
      puts "pattern[expr {$p + 1}] [lindex $pattern_index $p]"
    }

}

上述代码的输出:

Row1 A B C D
pattern number = 4
pattern1 A
pattern2 B
pattern3 C
pattern4 D

Row2 P Q R S
pattern number = 4
pattern1 P
pattern2 Q
pattern3 R
pattern4 S

Row3 W X Y 
pattern number = 3
pattern1 W
pattern2 X
pattern3 Y

相反,我希望代码给我如下输出:

Row1 A B C D
pattern number = 4
pattern1 A
pattern2 B
pattern3 C
pattern4 D

Row2 P Q R S
pattern number = 4
pattern5 P
pattern6 Q
pattern7 R
pattern8 S

Row3 W X Y 
pattern number = 3
pattern9 W
pattern10 X
pattern11 Y

请建议我该怎么做

4

1 回答 1

1
  1. 采用foreach
  2. 不要重置变量

所以你的代码变成:

set rownr 0
set patnr 0
foreach row $sub_list {
    incr rownr
    puts "Row$rownr $row"
    puts "pattern number = [llength $row]"
    foreach pattern $row {
        incr patnr
        puts "pattern$patnr $pattern"
    }
}

如果您想进一步处理此问题,请告诉我您的需要。
(我假设您真的不想动态生成变量名。)

于 2013-08-23T23:14:19.670 回答