[Tutor] Output of list
Martin Walsh
mwalsh at groktech.org
Sun Dec 23 20:40:13 CET 2007
János Juhász wrote:
> It is nice place to use a generator:
>
> def pairs(sliceit):
> streamlist = list(sliceit)
> streamlist.reverse()
> while streamlist:
> pair = streamlist.pop()
> try: pair += streamlist.pop()
> except: pass
> yield pair
>
> ## Probably it is easier to understand
> def pairs2(sliceit):
> try:
> while sliceit:
> yield sliceit[:2]
> sliceit = sliceit[2:]
> except: # oops, it was odd length
> yield sliceit
>
... Or, by extending Alan's solution ...
def splitStringByN(s, n):
for m in range(0, len(s), n):
yield s[m:m+n]
k = 'abcdefghi'
list(splitStringByN(k, 2))
As it turns out, this is similar to an ASPN Cookbook recipe contributed
by Dmitry Vasiliev:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/302069
HTH,
Marty
More information about the Tutor
mailing list