在TCL中动态创建嵌套列表

时间:2019-07-02 14:52:56

标签: tcl ns2

我正在NS2中使用Tcl,试图基于项目总数创建嵌套列表。例如,我有20个项目,因此我需要在allLists {}列表中创建20个列表,以后可以使用诸如puts "[lindex $allLists 0 2]"之类的方法添加某些值。下面是我的代码:

for {set i 0} {$i < $val(nn)} {incr i} {
    set allClusters {
        set nodeCluster [lindex $allClusters $i] {}
    }
}
puts "$allClusters" 
puts "Node Cluster 0: [lindex $nodeCluster 0]"

我的预期输出将是20个空白列表,并为nodeCluster 0增加1个:

{}
{}
{}
...
Node Cluster 0: {}

相反,我将其作为引号得到:

set nodeCluster [lindex $allClusters $i] {}

一个,我不想手动设置嵌套列表,因为稍后在$allLists中将有100个列表。第二,如果没有值附加到嵌套列表,我最终将不创建嵌套列表。

如何为变化的值创建嵌套列表?

1 个答案:

答案 0 :(得分:3)

我还没有完全理解这个问题,但是根据我的理解,您需要创建一个列表列表,其中较大的列表包含20个较小的列表。您也许可以使用类似这样的东西:

set allClusters [list]
set subClusters [list]
for {set i 0} {$i < 20} {incr i} {
    lappend subClusters [list]
}
lappend allClusters $subClusters

puts $allClusters
# {{} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {}}

$allClusters是20个较小列表的列表。

如果随后要为索引2处的较小列表设置值,则必须先提取较小的列表,然后lappend提取到该列表,然后放回原处:

set subCluster [lindex $allClusters 0 2]
lappend subCluster "test"
lset allClusters 0 2 $subCluster

您可以创建一个proc来完成上述操作:

proc deepLappend {clusterName indices value} {
    upvar $clusterName cluster
    set subCluster [lindex $cluster {*}$indices]
    lappend subCluster $value
    lset cluster {*}$indices $subCluster
}

deepLappend allClusters {0 2} "test"
deepLappend allClusters {0 2} "test"

puts $allClusters
# {{} {} {test test} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {}}

尽管要创建一组空列表,也可以尝试使用lrepeat

set allClusters [list [lrepeat 20 [list]]]
# {{} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {}}