Re: better way to write this function
- From: Peter Otten <__peter__@xxxxxx>
- Date: Mon, 26 Nov 2007 09:19:21 +0100
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:
.... return [items[start:start+n] for n in range(0, len(items)-n+1, n)]def chunks(items, n):
....
.... print chunks(range(5), i)for i in range(1,10):
....
[[0], [1], [2], [3], [4]]
[[0, 1], [2, 3]]
[[0, 1, 2]]
[[0, 1, 2, 3]]
[[0, 1, 2, 3, 4]]
[]
[]
[]
[]
Or build a generator that works with arbitrary iterables:
.... items = iter(items)from itertools import *
def chunks(items, n):
.... while 1:
.... chunk = list(islice(items, n-1))
.... chunk.append(items.next())
.... yield chunk
....
[[0, 1], [2, 3]]list(chunks(range(5), 2))
Peter
.
- Follow-Ups:
- Re: better way to write this function
- From: Arnaud Delobelle
- Re: better way to write this function
- From: Peter Otten
- Re: better way to write this function
- From: Ricardo Aráoz
- Re: better way to write this function
- References:
- better way to write this function
- From: Kelie
- better way to write this function
- Prev by Date: Re: How to display unicode with the CGI module?
- Next by Date: Re: How to display unicode with the CGI module?
- Previous by thread: better way to write this function
- Next by thread: Re: better way to write this function
- Index(es):
Relevant Pages
|