map, filter, reduce, zip, range, and.. slice?

George Demmy gdemmy at layton-graphics.com
Thu Nov 1 18:17:49 CET 2001


eddie at holyrood.ed.ac.uk (Eddie Corns) writes:

> Eyal Lotem <eyal at hyperroll.com> writes:
> 
> >Hey.  Recently, I've been heavily using functional-style programming in 
> >Python, doing almost all of my text processing and so with complex nested 
> >lambda clauses.  I love those, as they are so short, and seem to work with 
> >a painless "debug" cycle, usually consisting of some missing reduce initial 
> >value or so.
> 
> >To get to the point, I've almost always lacked a 'slice' function, that 
> >slices sequences into smaller chunks.  For example:
> 
> >divide("Hello world!", 2) => ["He", "ll", "o ", "wo", "rl", "d!"]
> 
> It's a bit clumsy but how about:
> 
> [x[i:i+2] for i in range(0,len(x),2)]
> 
> Where x is your string.
> 
> Eddie

Eddie's solution in the lambda notation...

divide = lambda x,s=1: [ x[i:i+s] for i in range(0,len(x),s) ]

In action...

>>> hi = 'hello, world'
>>> for i in range(1,len(hi)+1):
...   divide(hi,i)
... 
['h', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd']
['he', 'll', 'o,', ' w', 'or', 'ld']
['hel', 'lo,', ' wo', 'rld']
['hell', 'o, w', 'orld']
['hello', ', wor', 'ld']
['hello,', ' world']
['hello, ', 'world']
['hello, w', 'orld']
['hello, wo', 'rld']
['hello, wor', 'ld']
['hello, worl', 'd']
['hello, world']


Love them lambdas...

G




More information about the Python-list mailing list