Elegantly subsplitting a sequence

Steve McAllister nosp at m.needed
Fri May 30 11:17:01 EDT 2003


The purpose being: {
subsplit(range(11), groupby=3)
-> [(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10)]

}, do you think of more beautiful a way than {

def subsplit(seq, groupby=1):
     return [tuple(seq[i:i+groupby])
             for i in range(0, len(seq), groupby)]
}?



And similarly, to provide a nice repr() of an integer, what about {

class Int:
     def __init__(self, int_): self.int_ = int_
     def __repr__(self, groupby=3, glue="'"):
         s = str(self.int_); n, v = len(s), []
         for i in range(0, n, groupby):
             v.insert(0, s[max(0, n-i-groupby):n-i])
         return glue.join(v)

import sys
print 'MAX_INT for this platform is %r' %Int(sys.maxint)
-> MAX_INT for this platform is 2'147'483'647
}?





More information about the Python-list mailing list