如何在Tcl中检索数组键值



给定数据

array set color {a red b green c blue}
set keylist [array names $color]
pointlist  {{1 2 3 4} {5 6 7 8} {9 10 11 12} {13 14 15 16}}

运行程序后,我得到了一个新列表。

 newlist  {b b b b}     # Note: length of newlist is same as length of pointlist

问题是:当我运行一个循环时,这些b值应该被替换,例如在这个绿色中。

for {set i 0} { $i < [llength $pointlist]} {incr i } {
    lassign [lindex $pointlist $i] x1 y1 x2 y2
    APICommand -points "$x1,$y1,$x2,$y2" -color $color($keylist)
}

现在这个$color($keylist)并没有给我正确的结果,并错误地说:无法读取"颜色(红蓝绿)":阵列中没有这样的元素

相反,我希望第一组4点得到绿色,这是b的值。类似地,点列表中的下一组4点也应该得到绿色,因为它的值也是b。

 #So, after substitution it should look like APIcommand -points 1,2,3,4 -color green ..... so on and so forth

请注意,这并不总是b,只是碰巧在这种情况下。

需要尽快解决。提前谢谢。

听起来您需要$color([lindex $newlist $i])

在列表中迭代时,foreach命令非常有用。它还可以用于在多个相应的列表上进行迭代。假设newlist包含与点对应的颜色,我可能会尝试类似(关于未测试代码的常见警告):

foreach point $pointlist new $newlist {
    APICommand -points [join $point ,] -color $color($new)
}

最新更新