Re: better way to write this function
- From: Paul McGuire <ptmcg@xxxxxxxxxxxxx>
- Date: Mon, 26 Nov 2007 09:16:07 -0800 (PST)
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!
.... print j,':',[lst[i:i+j] for i in xrange(0,len(lst),j)]lst = list("ABCDE")
for j in range(1,6):
....
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:
.... print j,':',[lst[i:i+j] for i in xrange(0,len(lst),j) if ifor j in range(1,6):
+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:
[['A', 'B'], ['C', 'D'], ['E']]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']]chunksWithoutLeftovers(lst,2)
-- Paul
.
- References:
- better way to write this function
- From: Kelie
- better way to write this function
- Prev by Date: Re: Should proxy objects lie about their class name?
- Next by Date: Re: How to write Regular Expression for recursive matching?
- Previous by thread: Re: better way to write this function
- Next by thread: Re: better way to write this function
- Index(es):
Relevant Pages
|