Re: better way to write this function



On Nov 26, 1:42 am, Kelie <kf9...@xxxxxxxxx> wrote:
Hello,

This function does I what I want. But I'm wondering if there is an
easier/better way. To be honest, I don't have a good understanding of
what "pythonic" means yet.

def divide_list(lst, n):
"""Divide a list into a number of lists, each with n items. Extra
items are
ignored, if any."""
cnt = len(lst) / n
rv = [[None for i in range(n)] for i in range(cnt)]
for i in range(cnt):
for j in range(n):
rv[i][j] = lst[i * n + j]
return rv

Thanks!

lst = list("ABCDE")
for j in range(1,6):
.... print j,':',[lst[i:i+j] for i in xrange(0,len(lst),j)]
....
1 : [['A'], ['B'], ['C'], ['D'], ['E']]
2 : [['A', 'B'], ['C', 'D'], ['E']]
3 : [['A', 'B', 'C'], ['D', 'E']]
4 : [['A', 'B', 'C', 'D'], ['E']]
5 : [['A', 'B', 'C', 'D', 'E']]

Or if you want to discard the uneven leftovers:

for j in range(1,6):
.... print j,':',[lst[i:i+j] for i in xrange(0,len(lst),j) if i
+j<=len(lst)]
....
1 : [['A'], ['B'], ['C'], ['D'], ['E']]
2 : [['A', 'B'], ['C', 'D']]
3 : [['A', 'B', 'C']]
4 : [['A', 'B', 'C', 'D']]
5 : [['A', 'B', 'C', 'D', 'E']]

Or define a lambda:

chunksWithLeftovers = lambda lst,n: [lst[i:i+n] for i in xrange(0,len(lst),n)]
chunksWithoutLeftovers = lambda lst,n: [lst[i:i+n] for i in xrange(0,len(lst),n) if i+n<=len(lst)]
chunksWithLeftovers(lst,2)
[['A', 'B'], ['C', 'D'], ['E']]
chunksWithoutLeftovers(lst,2)
[['A', 'B'], ['C', 'D']]


-- Paul
.



Relevant Pages

  • better way to write this function
    ... easier/better way. ... To be honest, I don't have a good understanding of ... """Divide a list into a number of lists, ...
    (comp.lang.python)
  • Re: better way to write this function
    ... easier/better way. ... To be honest, I don't have a good understanding of ... def divide_list: ... """Divide a list into a number of lists, ...
    (comp.lang.python)
  • Re: better way to write this function
    ... To be honest, I don't have a good understanding of ... def divide_list: ... """Divide a list into a number of lists, ...
    (comp.lang.python)
  • Re: better way to write this function
    ... Kelie writes: ... easier/better way. ... To be honest, I don't have a good understanding of ... """Divide a list into a number of lists, ...
    (comp.lang.python)
  • Re: better way to write this function
    ... To be honest, I don't have a good understanding of ... def divide_list: ... """Divide a list into a number of lists, ...
    (comp.lang.python)