[portland] Need Help With a For Loop

Dylan Reinhardt dylanr at dylanreinhardt.com
Thu Mar 20 23:24:38 CET 2008


OK... I think I'm starting to grok the problem.

Taking this as a one-off, you might use a list comprehension to great effect
here.  If you don't know, a list comprehension basically executes some
operation on all elements of a collection and returns a list of results.
So, for example:

>>> a = 'hello'
>>> [i for i in a]
['h', 'e', 'l', 'l', 'o']

More complexly, you can return an element *and* the collection itself into a
list of tuples:

>>> [(i, a) for i in a]
[('h', 'hello'), ('e', 'hello'), ('l', 'hello'), ('l', 'hello'), ('o',
'hello')]

List comprehensions are especially useful in a case like this where you want
to re-pack sequence items in a way that makes sorting, filtering, or
grouping easier.

I think that might hold the key here.  You want a couple specific positions
in each tuple to be named, but also want access to the whole tuple.  So if
you try something like:

for arg1, arg2,  elems in [(i[4], i[8], i) for i in compList]:
     ...

Now the var named "arg1" corresponds with the element at position 4 in each
tuple.  You also have another name for a different position and even have a
ref to the whole tuple.  You would obviously choose more descriptive
names... but this pattern allows you to *mostly* keep the positional
references socked away in one place and deal with *names* everywhere else.

Longer term, though, I'd encourage you to use a class to store information
of this complexity, especially if you find yourself doing this kind of stuff
in more than one place.  That would allow you to write code like:

for item in collection:
    if item.curve == 'some value':
        item.plot(some_arg)
    ...

or even better, you could pack that logic into the class, such that you're
left with:

for item in collection:
    if item.some_property:
        item.plot()


HTH,

Dylan


On 3/20/08, Rich Shepard <rshepard at appl-ecosys.com> wrote:
>
> On Thu, 20 Mar 2008, Dylan Reinhardt wrote:
>
> > In most cases, I would strongly recommend ditching this idiom:
> >
> > for i in range(len(collection)):
> >    doSomething(collection[i])
> >
> > In favor of this one:
> >
> > for item in collection:
> >    doSomething(item)
>
>
> Dylan,
>
>    Tried this before but still could not get it correct. Just tried again,
> too. Here is a set of three tuples for the same parent variable. I want to
> loop through the three plotting the appropriate curve each time:
>
> [("Few","Abundance","Fish","Wildlife","Decay
> S-Curve",1,0.0,50.0,0.0,50.0,0.0,50.0,50.0,0.0,50.0,1.0,2),
> ("Moderate","Abundance","Fish","Wildlife","Bell
> pCurve",2,0.0,100.0,0.0,100.0,0.0,50.0,50.0,50.0,100.0,1.0,2),
> ("Many","Abundance","Fish","Wildlife","Growth
> S-Curve",3,50.0,100.0,50.0,50.0,0.0,50.0,50.0,100.0,50.0,1.0,2)]
>
>    The parent is "Abundance," the sequence number is item[4], the total
> number of curves to plot on the same set of axes is item[16], and item[4]
> is
> used to call the appropriate plotting function.
>
>    Starting like this does not work:
>
>         for item in compList:
>
>            pylab.hold(True)
>            if compList[0][4] == 'Decay S-Curve':
>              testFunctions.zCurve(compList[0][10],compList[0][9])
>            elif compList[0][4] == 'Bell Curve':
>              testFunctions.gaussCurve(compList[0][14],compList[0][14])
>            elif compList[0][4] == 'Growth S-Curve':
>              testFunctions.sCurve(compList[0][8],compList[0][11])
>
>           ...
>
>    I can't do 'for item[0][1] in compList:' because that generates
> "NameError: global name 'item' is not defined".
>
>
> Thanks,
>
> Rich
>
> --
> Richard B. Shepard, Ph.D.
> |  Integrity            Credibility
> Applied Ecosystem Services, Inc.        |            Innovation
> <http://www.appl-ecosys.com>     Voice: 503-667-4517      Fax:
> 503-667-8863
> _______________________________________________
> Portland mailing list
> Portland at python.org
> http://mail.python.org/mailman/listinfo/portland
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/portland/attachments/20080320/1eec4a20/attachment.htm 


More information about the Portland mailing list