Re: better way to write this function



Peter Otten wrote:
Kelie 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

You can use slicing:

def chunks(items, n):
... return [items[start:start+n] for n in range(0, len(items)-n+1, n)]
...
for i in range(1,10):
... print chunks(range(5), i)
...
[[0], [1], [2], [3], [4]]
[[0, 1], [2, 3]]
[[0, 1, 2]]
[[0, 1, 2, 3]]
[[0, 1, 2, 3, 4]]
[]
[]
[]
[]


This won't work(e.g. you don't define "start", you change the value of n
through the loop). I guess you meant :

def chunks(items, n) :
return [items[i:i+n] for i in range(0, len(items)-n+1, n)]





.



Relevant Pages

  • 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
    ... 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)
  • 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
    ... 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)