Zuckerberg
Zuckerberg

Reputation: 205

Split a List in TCL to two equally sized lists

Is there a better way other than

  1. Find the length of the list ([llength])
  2. Run a counter to Midway [llength]/2
  3. Then Pop out all elements [lindex $index] upto lindex/2
  4. then Do a intersect with the list in step 3 with Original list

It would be really nice if there is a less involved way to pop out one element in list1 and next element in list 2 etc .

Upvotes: 1

Views: 2830

Answers (2)

wolfhammer
wolfhammer

Reputation: 2661

You could use a foreach loop.

set pairedlist [list "FirstName" "Tony" "LastName" "Bennett"]

set keys [list]
set values [list]

foreach {key value} $pairedlist {
  puts "$key: $value"
  lappend keys $key
  lappend values $value
}

puts $keys
puts $values

Upvotes: 0

kostix
kostix

Reputation: 55443

set len [expr {[llength $src] / 2}]
set left [lrange $src 0 [expr {$len - 1}]]
set right [lrange $src $len end]

You might also first check that the full length is an even number greater or equal than two.

Upvotes: 3

Related Questions