Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Re: Slicing iterables in sub-generators without loosing elements

Reply
Thread Tools

Re: Slicing iterables in sub-generators without loosing elements

 
 
Ian Kelly
Guest
Posts: n/a
 
      09-29-2012
On Sat, Sep 29, 2012 at 10:14 AM, Thomas Bach
<(E-Mail Removed)-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.
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Slicing iterables in sub-generators without loosing elements Thomas Bach Python 19 10-03-2012 03:21 AM
Elementwise -//- first release -//- Element-wise (vectorized)function, method and operator support for iterables in python. Nathan Rice Python 10 12-21-2011 05:22 PM
Python 3000 idea -- + on iterables -> itertools.chain John Reese Python 10 11-14-2006 12:22 AM
Strange behavior with iterables - is this a bug? akameswaran@gmail.com Python 7 05-31-2006 04:14 PM
*expression and iterables Steven Bethard Python 0 08-20-2004 06:09 AM



Advertisments