开发者

remove a sublist from list in tcl

开发者 https://www.devze.com 2023-04-12 11:51 出处:网络
I want to remove a sublist开发者_运维问答 from a list in Tcl. I know how to do it for main list using lreplace but I don\'t know how to do it for a sublist.

I want to remove a sublist开发者_运维问答 from a list in Tcl. I know how to do it for main list using lreplace but I don't know how to do it for a sublist. For example:

set a { 1 2  { {3 4} { 4 } } }

Now I want to remove {4} from internal list { {3 4} {4} }. The final list should be:

a { 1 2  { {3 4} } }

Please suggest how to dot his.


Combine lindex to get the internal sublist, lreplace to delete an element of the extracted internal sublist and lset to put the modified sublist back in place.

But honestly I have a feeling something's wrong about your data model.


proc retlist {a} {
    set nl ""
    foreach i $a {
        if {[llength $i] > 1} {
            set nl2 ""
            foreach i2 $i {
                if {[llength $i2] > 1} { lappend nl2 $i2 }
            }
            lappend nl $nl2
        } else {
            lappend nl $i
        }
    }
    return $nl
}

If you need variable depth you're lost with this code. You need recursion for that.

% set a {1 2 {{3 4} {5}}}
1 2 {{3 4} {5}}
% retlist $a
1 2 {{3 4}}

As the outer list is never displayed in tclsh.


It requires a few tricks to do nicely:

proc lremove {theList args} {
    # Special case for no arguments
    if {[llength $args] == 0} {
        return {}
    }
    # General case
    set path [lrange $args 0 end-1]
    set idx [lindex $args end]
    lset theList $path [lreplace [lindex $theList $path] $idx $idx]
}

set a [lremove $a 2 1]

This works because both lset and lindex can take paths, and they do sensible things with an empty path too.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号