TCL数组或List Manipulation到变量

时间:2013-01-16 23:04:35

标签: tcl

以下TCL函数被调用n次。每次将numid和type传递给此函数时,我都试图为每种类型添加numid。

例如

如果传递的值如下

2       BLACK
1       RED
1       BLACK
3       BLUE
1       BLUE
2       BLUE
2       RED

我得到的输出是使用set_numid_type函数

black_color_str 2 1
red_color_str 1 2
blue_color_str 3 1 2

但我需要的输出如下。当type不按顺序时,它应该附加到不同的变量类型。

black_color_str 2 
red_color_str 1
black_color_str 1
blue_color_str 3 1 2 (since BLUE color is called in sequence)
red_color_str 2



proc set_numid_type {numid type} {

  variable black_color_str
  variable red_color_str
  variable blue_color_str

  if {$type == "BLACK"} {

      if {![info exists black_color_str] || ![llength $ black_color_str]} {
          set black_color_str ""
          }

       lappend black_color_str $numid
   }

   if {$type == "RED"} {

      if {![info exists red_color_str] || ![llength $ red_color_str]} {
          set red_color_str ""
         }

       lappend red_color_str $numid
   }

   if {$type == "BLUE"} {

      if {![info exists blue_color_str] || ![llength $ blue_color_str]} {
          set blue_color_str ""
          }

       lappend blue_color_str $numid
   }

}

1 个答案:

答案 0 :(得分:0)

这是一个在输入列表上运行并返回输出列表的版本。 如果你真的想要,你可以修改它以处理全局变量。

proc GroupSequences { inputPairs } {
    if {[llength $inputPairs] == 0} return {}       
    set sequences {}
    set lastColour ""
    set latestSequence {}
    foreach pair $inputPairs {
        puts 1
        if {"[lindex $pair 1]" != $lastColour} {
            puts 2
            if {[llength $latestSequence] > 0} {
                puts 3
                lappend sequences $latestSequence
            }
            puts 4
            set latestSequence [lreverse $pair]
            set lastColour [lindex $pair 1]
        } else {
            puts 5
            lappend latestSequence [lindex $pair 0]
        }
    }
    puts 6
    lappend sequences $latestSequence
    return $sequences
}

set input [list { 2 "black" } { 1 "red" } { 1 "black" } {3 "blue" } { 1 "blue" } { 2 "blue" } { 2 "red" } ]
set seq [GroupSequences $input]
相关问题