how to remove emty elements from tcl list

2019-06-25 13:02发布

问题:

hi I have following list

% set qprList {{{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} 12345 {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} 12345 {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} 12345 {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} 12345 {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}} {{}}}

I want to remove all the elements which are empty. since list of list is i am not able to do it in single loop interation.

Any simple way to achieve this?

回答1:

There are no empty elements in that list. The ones that seem empty can be considered as (a) a string "{}" or (b) a list with one element which is an empty string or an empty list.

package require struct::list
set non_empty [struct::list filter \
                 [struct::list flatten $qprList] \
                 {apply {{x} {expr {[string length $x] > 0}}}} \
              ]


回答2:

You might also try this:

set listwithoutnulls [lsearch -all -inline -not -exact $listwithnulls {}]

It doesn't require a package include. It, too, can be re-applied.



回答3:

Coming from the Tclers Wiki (http://wiki.tcl.tk/440):

To flatten a list:

concat {*}$nested

It can be applied multiple times:

proc flatten data { concat {*}$data }

set a {{a {b c}} {d {e f}}} ; # {a {b c}} {d {e f}} flatten $a ; # a {b c} d {e f} flatten [flatten $a] ; # a b c d e f



回答4:

I also use struct::list because I am lazy:

package require struct::list
set non_empty [struct::list flatten -full $qprList]


标签: list null tcl