comp.lang.tcl
[Top] [All Lists]

Re: How to turn a very long list into smaller lists

Subject: Re: How to turn a very long list into smaller lists
From: miguel
Date: Fri, 30 May 2008 12:02:52 -0300
Newsgroups: comp.lang.tcl


Jonathan Bromley wrote:
On Fri, 30 May 2008 07:30:40 -0700 (PDT), Mel wrote:

I have a list that is very long and I need to break it into smaller
lists of say 50 elements (the original list is a muliple of 50.

as for now I am just using lrange function which is extremy slow on a
long list of say 100000 items.

On my not-very-fast Windows PC, this proc breaks up a list of 1,000,000 elements into a list of 20,000 fifty-element
lists, in about an eighth of a second.  Is that too slow for
you?  I was quite impressed...

proc split_list {L {n 50}} {
  incr n 0; # thanks to RS for this cool "is it an int" check!
  set result {}
  set limit [expr {[llength $L] - $n}]
  for {set p 0} {$p <= $limit} {incr p $n} {
    lappend result [lrange $L $p [expr {$p+$n-1}]]
  }
  return $result
}

What are you doing that is "extremely slow" ?  I suspect
you are doing something that causes the list to be shimmered back and forth between list and string representation internally.

... or else cause it to be copied multiple times? Like

  (1) extract first 50 elements
  (2) reset the list to the last (length - 50) elements
  (3) if not done goto (1)

Step (2) causes a copy followed by discarding the original, and that could be 
costly

<Prev in Thread] Current Thread [Next in Thread>
Privacy Policy