Python equivalent to Ruby each_slice (count)

What is the Ruby python equivalent each_slice(count)?
I want to take 2 items from a list for each iteration. As for [1,2,3,4,5,6], I want to process 1,2in the first iteration, then 3,4, then 5,6.
Of course, there is a roundabout way using index values. But is there a direct function or somehow do it directly?

+5
source share
4 answers

There is a recipe for this in the itertools documentation called grouper:

from itertools import izip_longest
def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

Use this:

>>> l = [1,2,3,4,5,6]
>>> for a,b in grouper(2, l):
>>>     print a, b

1 2
3 4
5 6
+9
source

, Mark, 'each_slice' python 2 3:

try:
    from itertools import izip_longest  # python 2
except ImportError:
    from itertools import zip_longest as izip_longest  # python 3

def each_slice(iterable, n, fillvalue=None):
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)
+2

ruby ​​each_slice -:

def each_slice(size, iterable):
    """ Chunks the iterable into size elements at a time, each yielded as a list.

    Example:
      for chunk in each_slice(2, [1,2,3,4,5]):
          print(chunk)

      # output:
      [1, 2]
      [3, 4]
      [5]
    """
    current_slice = []
    for item in iterable:
        current_slice.append(item)
        if len(current_slice) >= size:
            yield current_slice
            current_slice = []
    if current_slice:
        yield current_slice

(.. [5, None]), , .

0

: n, n None. , :

def each_slice(iterable, n, fillvalue=None):
    args = [iter(iterable)] * n
    raw = izip_longest(fillvalue=fillvalue, *args)
    return [filter(None, x) for x in raw]

, ALL None , , None .

0

All Articles