本文介绍了将元素追加到TCL中的嵌套列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想动态地将元素添加到嵌套列表中.考虑以下示例:
I want to dynamically add elements to nested lists. Consider the following example:
set super_list {}
lappend super_list {00 01 02}
lappend super_list {10 11 12}
lappend super_list {20 21}
导致:
super_list = {00 01 02} {10 11 12} {20 21}
[lindex $super_list 0] = {00 01 02}
[lindex $super_list 1] = {10 11 12}
[lindex $super_list 2] = {20 21}
如何在[lindex $ super_list 2]后面附加另一个值(例如22)?
How do I append another value (e.g. 22) to [lindex $super_list 2]?
lappend [lindex $super_list 2] 22
不起作用!
到目前为止,我唯一想到的解决方法是:
The only workaround I could think of so far is:
lset super_list 2 [concat [lindex $super_list 2] {22}]
这真的是唯一的方法吗?
Is this really the only way?
谢谢,莱纳斯(Linus)
Thanks,Linus
推荐答案
在Tcl 8.6中(已添加功能;在早期版本中不起作用),可以使用lset
通过索引:
In Tcl 8.6 (the feature was added; it doesn't work in earlier versions) you can use lset
to extend nested lists via the index end+1
:
set super_list {{00 01 02} {10 11 12} {20 21}}
lset super_list 2 end+1 22
puts [lindex $super_list 2]
# ==> 20 21 22
您也可以通过使用数字索引来解决末尾的问题,但是我认为end+1
更易记.
You could address one past the end by using a numeric index too, but I think end+1
is more mnemonic.
这篇关于将元素追加到TCL中的嵌套列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!