Python how to use map () to split a list into sublists?

I have this function for dividing iterations into sublists by length, fill values ​​and fill direction:

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 liner, I want to rewrite it with a map, but I don't understand how. 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?

+3


source to share


1 answer


I think you are thinking too much. This problem can be successfully handled with a perch recipe without usingmap

def split1(v,size,fill=0,direction='right'):
    result = list(izip_longest(*[iter(l)]*size, fillvalue=fill))
    if direction == 'left':
        result[-1] = result[-1][::-1]
    return result

      

Explanation:

  • iter : This function converts a sequence to iterable. Iterants are consumable of their own and have only one method, next

    which returns the next item from the iterable, moving from left to right.
  • [iter(l)]*size

    : Creates a list of size

    iterables
  • * (Kleene star) : This operator is used to unpack a list or tuple
  • izip_longest : transposed elements. For shorter sequences, it is filled with a filled value
  • result[-1] = result[-1][::-1]

    : If the direction left

    cancels the previous sequence


Another possible popular solution without grouper is

def split2(v,size,fill=0,direction='right'):
    result = [v[i:i+size] for i in range(0,len(v),size)]
    result[-1] = result[-1] + [fill] * (size - len(result[-1]))
    if direction == 'left':
        result[-1] = result[-1][::-1]
    return result

      

Explanation:

  • Python Extended Snippet is used . The Slicing sequence has the following syntax[start: end: stride]

  • Python range returns a list (in Py2.x) and a range object (in Py 3.x) as a sequence / iterable starting from start

    , ending with end

    and stepping through the stride

    elements. Like(for int i = start; i < stop; i+= stride)

  • [fill] * (size - len(result[-1]))

    : generates items (size - len(result[-1]))

    fill

    as a list. If (size - len(result[-1]))

    equal to <= 0, it generates an empty list
  • result[-1] = result[-1] + [fill] * (size - len(result[-1]))

    - update last sequence with fill value
  • result[-1] = result[-1][::-1]

    : If the direction left

    cancels the previous sequence
+6


source







All Articles