[portland] Still Having List/Tuple Problems

jason kirtland jek at discorporate.us
Wed Apr 16 21:07:41 CEST 2008


Rich Shepard wrote:
>    I have a mental block on understanding just how to index a list of tuples
> so I can extract the data in an orderly fashion.
> 
>    The list looks like this: [(A,1),(A,2), ... (A,8),(B,1),(B,2), ...
> (B,8),(C,1),(C2), ... (C,8)]
> 
>    What I want to do is extract all tuples grouped by the first element, then
> list the associated second elements). That is,
> A
>  	1
>  	2
>  	...
>  	8
> 
> B
>  	1
>  	2
>  	...
>  	8
> etc.
> 
>    Referencing list[0] returns the first tuple; list[0][0] returns the first
> item in the first tuple; but I cannot cycle through the three first items
> extracting the second items associated with each.
> 
>    I've looked at my books and previous threads here, but I'm just not
> getting how this is done. I've played with list comprehensions, zip, and
> other tools without getting the proper syntax or results I need. Don't know
> why the answer keeps eluding me, but it does.

A, B, C = 'A', 'B', 'C'

list_o_tuples = [
     (A,1), (A,2), (A, '...'), (A,8),
     (B,1), (B,2), (B, '...'), (B,8),
     (C,1), (C,2), (C, '...'), (C,8)]

# option 1) charge through the flat list and keep a flag
previous = None
for left, right in list_o_tuples:
     if left != previous:
         print left
         previous = left
     print "\t", right


# option 2) make groups, each sharing a common 'left' item
from itertools import groupby
from operator import itemgetter

for left, grouped in groupby(list_o_tuples, itemgetter(0)):
     print left
     for left_again, right in grouped:
         print "\t", right

# look under the hood at what groupby() does in 2)
for left, grouped in groupby(list_o_tuples, itemgetter(0)):
     print left, list(grouped)


More information about the Portland mailing list