列表元素自身增量

Chr*_*Bao 2 list tcl increment

对于其他语言,列表元素的自增是非常容易的,就像:

list1(i) = list1(i) + 1
Run Code Online (Sandbox Code Playgroud)

但是对于tcl,目前我使用:

set temp [lindex $list1 $i];
lset list1 $i [expr $temp + 1];
Run Code Online (Sandbox Code Playgroud)

还有其他方法可以改善/简化它吗?

Din*_*esh 5

使用Tcl list,我不确定是否有任何内部命令可以直接增加list元素的值。

但是,如果您通过dict incr命令在Tcl中使用字典,则可以这样做。

dict incr dictionaryVariable key?increment?

这会将给定的增量值(如果未指定,则默认为1的整数)添加到给定键映射到给定变量所包含的字典值中的值,并将结果字典值写回到该变量。将不存在的键视为映射为0。将现有键的值增加为整数是错误的。返回更新的字典值。

set sample { firstName Dinesh lastName S title Mr age 23} 

# This will increase the value of 'age' by 1
puts [ dict incr sample age 2] 

# If any key used which does not exits in the dict, then it will create that key
# assume it's initial value is 0.

puts [ dict incr sample dob ]
Run Code Online (Sandbox Code Playgroud)

输出:

firstName Dinesh lastName S title Mr age 25
firstName Dinesh lastName S title Mr age 25 dob 1
Run Code Online (Sandbox Code Playgroud)

如果您仍然对在list元素中使用增量感兴趣,那么我们可以像下面这样编写一个新命令,

proc lincr { my_list index { increment 1 } } {
     upvar $my_list user_list
     if { [llength $user_list] <= $index } {
          return -code  error "Wrong list index"
     }  
     lset user_list $index [ expr {[lindex $user_list $index] + $increment} ]
}

set val { 1 2 3 4 } 
lincr val 1 4; # Increasing first index by 4
lincr val 0; #Increasing zeroth index by 1
puts $val
Run Code Online (Sandbox Code Playgroud)