better way to write this function

Chris cwitts at gmail.com
Mon Nov 26 03:36:54 EST 2007


On Nov 26, 9:42 am, Kelie <kf9... at gmail.com> 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!

x = ['1', '2', '3', '4', '5', '6', '7', '8']
def divide_list(lst, n):
    rv = []
    for i in range(int(round((len(lst)/n),0))):
        rv.append(lst[i*n:(i+1)*n])
    return rv

tmp = divide_list(x, 3)
tmp
[['1', '2', '3'], ['4', '5', '6']]

One way to do it.



More information about the Python-list mailing list