TCL中的lreplace和for循环查询

lreplace and for loop query in TCL

我能否请求帮助理解或强调为什么我无法在以下代码中循环 lreplace

oldlist = {} {} {} {} {} {} {} {} {} {Fred 1}
data_idx = 0 3 6
data_len = 3

for {set i 0} {$i < $data_len} {incr i} {
set idx_Fname [lindex $data_idx $i]
puts "ids($i) = $idx_Fname"
set NewList [lreplace $oldlist $data_idx $data_idx foo]
}

我希望看到

NewList = foo {} {} foo {} {} foo {} {} {Fred 1}

相反,我看到了

NewList = {} {} {} {} {} {} foo {} {} {Fred 1}

即只有最后一次迭代传递给 lreplace。

如果我尝试在 lreplace 中索引 $data_idx 即 $data_idx($i),则 $data_idx 不是数组会出现错误。

如果有人能指出错误,将不胜感激。

谢谢。

那是因为你在每次迭代后 create/rewrite NewList 变量。因此,在第一次迭代之后 NewList 变量包含:

NewList = foo {} {} {} {} {} {} {} {} {Fred 1}

第二个之后包含:

NewList = {} {} {} foo {} {} {} {} {} {Fred 1}

在第三个之后包含:

NewList = {} {} {} {} {} {} foo {} {} {Fred 1}

我想你的意思是这样的:

set NewList $oldlist
for {set i 0} {$i < $data_len} {incr i} {
    set idx_Fname [lindex $data_idx $i]
    puts "ids($i) = $idx_Fname"
    set NewList [lreplace $NewList $data_idx $data_idx foo]
}

您可以使用更简单的迭代构造 (foreach) and using lset.

set oldlist [list {} {} {} {} {} {} {} {} {} {Fred 1}]
set data_idx [list 0 3 6]

foreach idx $data_idx {
    lset oldlist $idx foo
}
puts $oldlist
  • foreach 不需要您维护计数器变量。
  • lset 作用于包含列表的给定变量,而不是变量的列表值,以就地修改列表。