Get the index in a structure array

2019-09-20 04:55发布

I have this structure array which is in tcl

A={1 2 3} { 4 5 6 } {7 8 9} {1 4 10}

I would like to get the structure indices which contain the number 4 which should be 2 , and 4 in A; how could I do it?

Also after i was able to get that indices , i'd like to remove those structures so that

A={1 2 3}{7 8 9}

How could I do that ?

Thanks !

标签: arrays tcl
2条回答
We Are One
2楼-- · 2019-09-20 05:36

[lmap] can help with that. [continue] allows you to skip the item:

set A {{1 2 3} {4 5 6} {7 8 9} {1 4 10}}
set B [lmap x $A {
                    if {[lsearch -exact $x 4] >= 0} {
                        continue
                    } else {
                        set x
                    }
                }]
    puts $B
查看更多
Ridiculous、
3楼-- · 2019-09-20 05:36
% array set myArr {
        1 {1 2 3}
        2 {4 5 6}
        3 {7 8 9}
        4 {1 4 10}
}
% parray myArr
myArr(1) = 1 2 3
myArr(2) = 4 5 6
myArr(3) = 7 8 9
myArr(4) = 1 4 10
% set num_to_find 4
4
% foreach idx [array names myArr] {
        # Checking if the array contains the number '4'
        if {[lsearch $myArr($idx) $num_to_find]!=-1} {
                # Keep track of the matched indices
                lappend matchIndices $idx
        }
}
% foreach idx $matchIndices {
        # Removing the array index based on the matched indices
        unset myArr($idx)
}
% parray myArr
myArr(1) = 1 2 3
myArr(3) = 7 8 9
%
%
查看更多
登录 后发表回答