0

我的 foreach 循环逻辑需要一些帮助:

除了循环中的最后一条语句外,我需要在每个打印语句之后放置一个逗号

前任:blah,blah2,blahlast

以下代码即使在最后一条语句之后也放置逗号。

 foreach row $regions {
            set name [lindex $row 0]
            set id [lindex $row 1]
            puts "{'name':'$name', 'val':'$region_id'}"
            puts ","

        }

也许如果我计算它循环的次数,我可能会检查一个 if 条件以将逗号放在最后一次迭代

4

3 回答 3

5

另一种方法是建立一个要打印的项目列表并在最后加入它:

set lines {}
foreach row $regions {
    set name [lindex $row 0]
    set region_id [lindex $row 1] ;# changed this from id to region_id, seemed right
    lappend lines "{'name':'$name', 'val':'$region_id'}"
}
puts [join $lines ",\n"]
于 2012-04-25T05:43:34.803 回答
3

诀窍是在除第一个迭代之外的所有迭代上打印逗号(也就是说,反转你的逻辑):

set xs {a b c}
set s ""
set need_comma false
foreach x $xs {
  if {$need_comma} {
    append s ,
  } else {
    set need_comma true
  }
  append s $x
}
puts $s

会产生

a,b,c

请注意,您似乎只是在寻找join命令。

于 2012-04-24T23:22:40.980 回答
0

I voted +1 for RHSeeger because that is what I would do. However, it seems you are trying to convert a TCL list to Python's list. If that is the case, you don't even have to worry about suppressing the last comma: Python allows that:

>>> li = [1,2,3,]
>>> len(li)
3

That means, your current solution works. Don't worry about the last comma.

于 2012-04-26T17:20:33.593 回答