Re: Slicing iterables in sub-generators without loosing elements

Discussion in 'Python' started by Ian Kelly, Sep 29, 2012.

  1. Ian Kelly

    Ian Kelly Guest

    On Sat, Sep 29, 2012 at 10:14 AM, Thomas Bach
    <-mainz.de> wrote:
    > Hi,
    >
    > say we have the following:
    >
    >>>> data = [('foo', 1), ('foo', 2), ('bar', 3), ('bar', 2)]

    >
    > is there a way to code a function iter_in_blocks such that
    >
    >>>> result = [ list(block) for block in iter_in_blocks(data) ]

    >
    > evaluates to
    >
    >>>> result = [ [('foo', 1), ('foo', 2)], [('bar', 3), ('bar', 2)] ]

    >
    > by _only_ _iterating_ over the list (caching all the elements sharing
    > the same first element doesn't count)?


    Am I correct in understanding that the intent is that the "blocks" are
    groups that share the same first item?

    Is it guaranteed that the blocks will be contiguous? If so, you could
    use itertools.groupby:

    from itertools import groupby, imap
    from operator import itemgetter

    def iter_in_blocks(data):
    return imap(itemgetter(1), groupby(data, itemgetter(0)))

    If there is no such guarantee, then the list would need to be sorted first.
    Ian Kelly, Sep 29, 2012
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Steven Bethard

    *expression and iterables

    Steven Bethard, Aug 20, 2004, in forum: Python
    Replies:
    0
    Views:
    388
    Steven Bethard
    Aug 20, 2004
  2. Replies:
    7
    Views:
    274
  3. Ben
    Replies:
    2
    Views:
    862
  4. Lawrence D'Oliveiro

    Death To Sub-Sub-Sub-Directories!

    Lawrence D'Oliveiro, May 5, 2011, in forum: Java
    Replies:
    92
    Views:
    1,969
    Lawrence D'Oliveiro
    May 20, 2011
  5. Thomas Bach
    Replies:
    19
    Views:
    264
    Ramchandra Apte
    Oct 3, 2012
Loading...

Share This Page