TCL列表和foreach问题
假设我有一个 TCL 列表:
set myList {}
lappend myList [list a b 1]
lappend myList [list c d 2]
.....
现在我想像这样修改列表:
foreach item $myList {
lappend item "new"
}
但最后我还没有修改列表。为什么?项目是列表项目上的参考吗?
Say I have a TCL list:
set myList {}
lappend myList [list a b 1]
lappend myList [list c d 2]
.....
Now I want to modify the list like this:
foreach item $myList {
lappend item "new"
}
But at the end I have not modified list. Why? item is a reference on the list item no?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
item
不是对列表项的引用。这是一个副本。为了做你想做的事,你可以这样做:item
is not a reference to the list item. It is a copy. To do what you want, you could do this:要“就地”编辑列表,您可以这样做:
如果您有 Tcl 8.6,您也可以这样做(请注意,我实际上并没有使用
$item
;这只是方便的循环) :但它不适用于 8.5,其中
lset
只会替换现有项目(和子列表)。To edit the list “in place”, you can do this:
You can also do this if you've got Tcl 8.6 (notice that I'm not actually using
$item
; it's just convenient looping):But it won't work on 8.5, where
lset
will only replace existing items (and sublists).如果您的列表非常大,则可以提高一些效率(例如K 组合器)。他们只会增加这里的复杂性。
If your list is very large, some efficiencies can be made (e.g. the K combinator). They would just add complexity here.
您在这里所做的就是获取一个变量(称为 item),并将其修改为也包含“new”。基本上,您会得到类似于
{a new}
、{b new}
等的列表。但是你会在每次迭代结束时泄漏这些变量。当你完成后,你真正希望你的清单是什么样子?
What you're doing here, is getting a variable (called item), and modifying it to also contain 'new'. basically, you get lists that look like
{a new}
,{b new}
and so on. But you leak those variables at the end of each iteration.What do you really want your list to look like when you're done?