[portland] Iterating Through Tuples In A List

jason kirtland jek at discorporate.us
Fri Feb 15 21:43:36 CET 2008


Rich Shepard wrote:
>    I've not yet figured out the code that gives me what I need in this one
> method. I'm sure it's simple, but the proper approach eludes me.
> 
>    Data start with a list of tuples. I iterate through the list and extract
> each tuple using,
> 
> for i in range(len(self.appData.tsets)):
>        self.row = self.appData.tsets[i]
> 
>    For the sake of discussion, each tuple (self.row) contains a component, a
> subcomponent, the subcomponent's sequential number, and the total number of
> subcomponents in the component. So there are multiple tuples for each
> component.
> 
>    What I need to do is iterate through components. For each component, I
> want to call a plotting routine for the subcomponents, in sequential order,
> to the total number of subcomponents. The tuples are in the proper order.
> 
>    I've not succeeded in writing the code to do the above. If I print the
> components and the total number of subcomponents, for example, I get output
> like this:
> 
> HabitatComplexity       2
> HabitatComplexity       2
> SpecialConcern  3
> SpecialConcern  3
> SpecialConcern  3
> Variety         2
> Variety         2
> 
> If I print the compnent, total of subcomponents, subcomponent sequential
> number, and subcomponent curve shape I get output like this:
> 
> HabitatComplexity       2       1       Decay S-Curve
> HabitatComplexity       2       2       Growth S-Curve
> SpecialConcern  3       1       Decay S-Curve
> SpecialConcern  3       2       Bell Curve
> SpecialConcern  3       3       Growth S-Curve
> Variety         2       1       Decay S-Curve
> Variety         2       2       Growth S-Curve
> 
>    I need to call the plotting library for each component, for the maximum
> number of subcomponents, so that all subcomponents are plotted on the same
> set of axes. This is what I've not yet figured out how to do.
> 
> Suggestions appreciated,

the groupby function in itertools is one way:

rows = [('HabitatComplexity',2,1,'Decay S-Curve'),
         ('HabitatComplexity',2,2,'Growth S-Curve'),
         ('SpecialConcern',3,1,'Decay S-Curve'),
         ('SpecialConcern',3,2,'Bell Curve'),
         ('SpecialConcern',3,3,'Growth S-Curve'),
         ('Variety',2,1,'Decay S-Curve'),
         ('Variety',2,2,'Growth S-Curve'),]

from operator import itemgetter
from itertools import groupby

for component, grouped in groupby(rows, key=itemgetter(0)):
     print component
     for row in grouped:
         print "\t%s" % row[3]

# this prints:
#
#HabitatComplexity
#        Decay S-Curve
#        Growth S-Curve
#SpecialConcern
#        Decay S-Curve
#        Bell Curve
#        Growth S-Curve
#Variety
#        Decay S-Curve
#        Growth S-Curve




More information about the Portland mailing list