Reputation: 99
Converting List of list into single list. for example:
List1 {1 2 {3 4 5} 6 7 {8} 9 10 {{11 12} 13} 14 {15} 16 {{{{17} 18} 19} 20} 21 22 {23} 24 25}
convert to
List1 { 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25}
How to convert it??
Upvotes: 0
Views: 990
Reputation: 246807
With tcllib:
package require struct::list
set List1 {1 2 {3 4 5} 6 7 {8} 9 10 {{11 12} 13} 14 {15} 16 {{{{17} 18} 19} 20} 21 22 {23} 24 25}
puts [struct::list flatten -full $List1]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
Upvotes: 1
Reputation: 137567
Provided the leaves are simple words (e.g., letters, numbers, periods, but absolutely no Tcl metacharacters) it's fairly simple with join
:
set s {1 2 {3 4 5} 6 7 {8} 9 10 {{11 12} 13} 14 {15} 16 {{{{17} 18} 19} 20} 21 22 {23} 24 25}
while {[set t [join $s]] ne $s} {set s $t}
puts $s
# => 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
To see how this works, try putting a puts
inside the loop, as in this interactive session:
% while {[set t [join $s]] ne $s} {
puts $t
set s $t
}
1 2 3 4 5 6 7 8 9 10 {11 12} 13 14 15 16 {{{17} 18} 19} 20 21 22 23 24 25
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 {{17} 18} 19 20 21 22 23 24 25
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 {17} 18 19 20 21 22 23 24 25
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
Note that this will not work if you produce an invalid list at any point during the expansion, hence why it is important to avoid metacharacters (especially \
, {
and }
). It's also not usual to do this sort of thing in production code; needing it is usually an indication of something elsewhere having gone wrong.
Upvotes: 0