如何在 TCL 中查找数组行中的列数
How to find number of columns in row for array in TCL
我的数组 cb_node
的列数不同。要post-处理这个数据,要求是准确知道每行中的列数。
数组如下所示。
cb_node(1,1) value
cb_node(1,2) value
...
cb_node(1,256) value
cb_node(2,1) value
....
cb_node(2,56) value
等等..
数组中的每一行都有不同数量的列。 value
只是示例,数组中的键不同。
TCL中的命令集只有array get cb_node
和array size cb_node
,没有给出每一行的行号和列号。
我们如何在 TCL 中做到这一点?
如果您不知道有多少行或多少列,但您知道没有跳过的行,只要 info exists
为真,您就可以循环:
#!/usr/bin/env tclsh
array set cb_node {1,1 a 1,2 b 1,3 c 2,1 d 3,1 e 3,2 f}
for {set row 1} {[info exists cb_node($row,1)]} {incr row} {
for {set col 1} {[info exists cb_node($row,$col)]} {incr col} {
puts "cb_node($row,$col) = $cb_node($row,$col)"
}
}
这将打印出来
cb_node(1,1) = a
cb_node(1,2) = b
cb_node(1,3) = c
cb_node(2,1) = d
cb_node(3,1) = e
cb_node(3,2) = f
如果键中的 1
表示行号,那么你也许可以这样使用:
set rowNum 1
set noOfColumns [llength [array names cb_node $rowNum,*]]
set count {}
foreach key [array names cb_node] {
lassign [split $key ,] row col
dict incr count $row
}
dict for {row n} $count {
puts "row $row has $n cols"
}
row 2 has 56 cols
row 1 has 256 cols
我的数组 cb_node
的列数不同。要post-处理这个数据,要求是准确知道每行中的列数。
数组如下所示。
cb_node(1,1) value
cb_node(1,2) value
...
cb_node(1,256) value
cb_node(2,1) value
....
cb_node(2,56) value
等等..
数组中的每一行都有不同数量的列。 value
只是示例,数组中的键不同。
TCL中的命令集只有array get cb_node
和array size cb_node
,没有给出每一行的行号和列号。
我们如何在 TCL 中做到这一点?
如果您不知道有多少行或多少列,但您知道没有跳过的行,只要 info exists
为真,您就可以循环:
#!/usr/bin/env tclsh
array set cb_node {1,1 a 1,2 b 1,3 c 2,1 d 3,1 e 3,2 f}
for {set row 1} {[info exists cb_node($row,1)]} {incr row} {
for {set col 1} {[info exists cb_node($row,$col)]} {incr col} {
puts "cb_node($row,$col) = $cb_node($row,$col)"
}
}
这将打印出来
cb_node(1,1) = a
cb_node(1,2) = b
cb_node(1,3) = c
cb_node(2,1) = d
cb_node(3,1) = e
cb_node(3,2) = f
如果键中的 1
表示行号,那么你也许可以这样使用:
set rowNum 1
set noOfColumns [llength [array names cb_node $rowNum,*]]
set count {}
foreach key [array names cb_node] {
lassign [split $key ,] row col
dict incr count $row
}
dict for {row n} $count {
puts "row $row has $n cols"
}
row 2 has 56 cols
row 1 has 256 cols