I have this function to split iterables into sublists by length, the fill values, and the direction of fill :
def split(v,size,fill=0,direction='right'):
if size == 0: return []
lenv = len(v)
count = lenv/size
remainder = lenv%size
result = []
for i in range(0,lenv-remainder,size):
result.append(v[i:i+size])
if remainder > 0:
if direction == 'right':
result.append(v[count*size:] + [fill] * (size-remainder))
else:
result.append([fill] * (size-remainder) + v[count*size:])
return result
Because I like one liners I want to rewrite it with map, but I don’t understand how to. I have this so far :
def j1(a,b):
return a + b
def j2(a,b):
return b
def split2(v,size,fill=0):
map(j1,(x for x in map(j2,v)))
I have no idea. Any hints?
I believe you are thinking too much. This problem can be aptly handled using the grouper recipe without using
mapExplanation:
nextwhich returns the next element from the iterable, moving from left to right.[iter(l)]*size: Creates a list ofsizeiterablesresult[-1] = result[-1][::-1]: If the direction isleftreverse the last sequenceAnother possible popular solution without grouper is
Explanation:
[start: end: stride]start, ending atendand steppingstrideelements. Similar to(for int i = start; i < stop; i+= stride)[fill] * (size - len(result[-1])): Generates(size - len(result[-1]))fillelements as a list. If(size - len(result[-1]))is <=0 it generates an empty listresult[-1] = result[-1] + [fill] * (size - len(result[-1]))– Update the last sequence with the fill valueresult[-1] = result[-1][::-1]: If the direction isleftreverse the last sequence