Re: better way to write this function
- From: Paul Hankin <paul.hankin@xxxxxxxxx>
- Date: Mon, 26 Nov 2007 11:08:46 -0800 (PST)
On Nov 26, 7: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!
Here's a terrible way to do it:
def divide_list(lst, n):
return zip(*[lst[i::n] for i in range(n)])
[It produces a list of tuples rather than a list of lists, but it
usually won't matter].
--
Paul Hankin
.
- References:
- better way to write this function
- From: Kelie
- better way to write this function
- Prev by Date: Re: Need to call functions/class_methods etc using string ref :How
- Next by Date: Re: the annoying, verbose self
- Previous by thread: Re: better way to write this function
- Next by thread: Re: Need to call functions/class_methods etc using string ref :How
- Index(es):
Relevant Pages
|