1

I want to group adjacent list items with fixed numbers. Such as

a = [1, 2, 3, 4, 5, 6]

The result of groupby(a, 2) is [(1, 2), (3, 4), (5, 6)],

The result of groupby(a, 3) is [(1, 2, 3), (4, 5, 6)]

Here are my solution

 def groupby(a, l):
    ret = []
    for idx in range(len(a)/l):
        ret.append(tuple(a[idx*l:(idx+1)*l:]))
    return ret

Is there more efficiently way to implement it?

zangw
  • 37,361
  • 17
  • 142
  • 172
  • Is it guaranteed that the length of the input list will be divisible by the grouping number? I.E. what should happen if the length of the list were 7? – SethMMorton Nov 05 '15 at 06:09
  • @SethMMorton, leave all the remains as the last group – zangw Nov 05 '15 at 06:12

3 Answers3

1
>>> a = [1, 2, 3, 4, 5, 6]
>>> groupby = lambda l, n: [tuple(l[i:i+n]) for i in range(0, len(l), n)] 
>>> groupby(a, 3)
[(1, 2, 3), (4, 5, 6)]
>>> groupby(a, 2)
[(1, 2), (3, 4), (5, 6)]
>>> 
Remi Guan
  • 20,142
  • 17
  • 60
  • 81
0

Yes, you're going to want to use zip.

EDIT: fixed formatting

Specifically,

def groupby(a, l):
  ret = []
  n = len(a) // l
  it = len(a) // n
  return list(zip(*(a[i * it:i * it + it] for i in range(n))))
personjerry
  • 1,006
  • 8
  • 26
0

We can do using itertools.izip_longest

Please check below link :

Alternative way to split a list into groups of n

Community
  • 1
  • 1
Harsha Biyani
  • 6,633
  • 9
  • 33
  • 55