我有一份超级清单,如:
set superlist {{1 2 3} {4 5 6} {7 8 9} {10 11 12} ...}
但我事先不知道我将有多少个子列表在超级列表中。是否存在要创建的子列表,如:
list1 {1 2 3}
list2 {4 5 6}
list3 {7 8 9}
...
我认为我必须根据超级列表中子列表的数量来创建变量列表名。有人能帮我解决这个问题吗,比如如何在执行代码时设置变量名?
发布于 2020-09-14 07:59:21
你可以这样做:
foreach sublist $superlist {
set list[incr index] $sublist
}
但不要!
在实践中,您几乎肯定会更喜欢使用数组。
foreach sublist $superlist {
set list([incr index]) $sublist
}
这样做的原因是使用变量索引进行访问的语法:
for {set index 1} {$index <= 3} {incr index} {
puts "at $index is the list $list($index)"
}
如果你用另一种方式去做,你必须使用一些更尴尬的东西,比如单参数的set
。
for {set index 1} {$index <= 3} {incr index} {
puts "at $index is the list [set list$index]"
}
(这是从一个名为BTW的变量中读取的最佳方式。)
https://stackoverflow.com/questions/63879951
复制相似问题