Re: better way to write this function



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
.



Relevant Pages

  • Re: 1 NF
    ... Oh, and anothe for lists. ... bags or lists simplies other things. ... least nested sets are possible because NF2 takes its queues from the ... by Def MV ==> NFNF aka NF2 ...
    (comp.databases.theory)
  • Re: [QUIZ] VCR Program Manager (#101)
    ... thought - oh, can't do lists, no pointers - but then I realized that ... def advance ... new_node.set_next @head ...
    (comp.lang.ruby)
  • Re: Efficient Rank Ordering of Nested Lists
    ... lists may be accomplished via: ... def rankList: ... If you find the for-clause too rich in functionality, ... Agreed that dict() approach looks promising. ...
    (comp.lang.python)
  • Re: Removing None objects from a sequence
    ... necessary and is algorithmically cleaner. ... def deNone2: ... lists to worry about. ... Here's another low-level algorithm, the classical delete items in place ...
    (comp.lang.python)
  • Re: [QUIZ] Port a Library (#64)
    ... # left and right lists differ from the original list. ... this function returns a reference to such an array. ... def Merge::diff3 ...
    (comp.lang.ruby)