gpt4 book ai didi

列表元素自增

转载 作者:行者123 更新时间:2023-12-02 17:45:22 24 4
gpt4 key购买 nike

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

list1(i) = list1(i) + 1

但对于 tcl,目前我使用:

set temp [lindex $list1 $i];
lset list1 $i [expr $temp + 1];

还有其他方法可以改进/使其更简单吗?

最佳答案

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

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

dict incr dictionaryVariable key ?increment?

This adds the given increment value (an integer that defaults to 1 if not specified) to the value that the given key maps to in the dictionary value contained in the given variable, writing the resulting dictionary value back to that variable. Non-existent keys are treated as if they map to 0. It is an error to increment a value for an existing key if that value is not an integer. The updated dictionary value is returned.

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 ]

输出:

firstName Dinesh lastName S title Mr age 25
firstName Dinesh lastName S title Mr age 25 dob 1

如果您仍然对在列表元素中使用增量感兴趣,那么我们可以编写一个新命令,如下所示,

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

关于列表元素自增,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26399525/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com