Welcome, guest | Sign In | My Account | Store | Cart

Simple versions what Hamish Lawson ("getting items in batches") and Brian QUinlan ("group list into n-tuples") submitted.

Iterables must support indexing and len(); doesn't use itertools.

Python, 22 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
def each_cons_iter(listin,n): 
"""(overlapp'g)moving window,return n items at a time from listin thru iterator"""
    i=0
    while (i<len(listin)-n+1 ):
        yield listin[i:i+n]
        i+=1
        
def each_slice_iter(listin,n):    
"""non-overlapp'g slices n elements at a time from listin,returned thru iterator"""
    i=0;        len_listin=len(listin)
    while (i<len_listin ):
        yield listin[i:min(len_listin,i+n)]
        i+=n
        
def each_cons_lol(listin,n):    
"""moving window, return (list of lists) of n items at a time"""
    return [listin[i:i+n] for i in range(len(listin)-n+1)]

def each_slice_lol(listin,n):        
"""non-overlapp'g slices, return (list of lists) """
    len_listin=len(listin)
    return [listin[i:min(len_listin, i+n)] for i in range(0,len_listin,n)]
Created by Gene tani on Fri, 26 Nov 2004 (PSF)
Python recipes (4591)
Gene tani's recipes (1)

Required Modules

  • (none specified)

Other Information and Tasks