split a list based on a predicate

Tim Chase python.list at tim.thechases.com
Thu Oct 9 01:52:26 CEST 2008


> Is there a functional way to do this?
> 
> I have an array [0,1,2,3,0,1,2,2,3] and I want the first chunk of
> non-decreasing values from this array (eg: In this case I want
> [0,1,2,3])


Sounds like a use for a generator wrapper:

   def monotonic(iterator):
     i = iter(iterator)
     prev = i.next()
     yield prev
     while True:
       this = i.next()
       if prev <= this:
         yield this
         prev = this
       else:
         break

   >>> lst1 = [0,1,2,3,0,1,2,2,3]
   >>> lst2 = [0,1,2,3,3,0,1,2,2,3]
   >>> print list(monotonic(lst1))
   [0,1,2,3]
   >>> print list(monotonic(lst2))
   [0,1,2,3,3]

Adjust the "<=" to "<" depending on your needs (my "lst2" 
condition probes that edge)

-tkc






More information about the Python-list mailing list