[portland] Need Help With a For Loop
Rich Shepard
rshepard at appl-ecosys.com
Thu Mar 20 23:46:36 CET 2008
On Thu, 20 Mar 2008, Dylan Reinhardt wrote:
> 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:
Dylan,
I thought a list comprehension would be the ticket, but my feeble efforts
got me nowhere.
> 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')]
I'll need to work with this, as it looks exactly what I want.
> 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:
The data are stored in a SQLite table; two tables, actually, and retrieved
with a SELECT statement into the list of tuples. For testing purposes I
copied the results into a static list.
I'm going to read again about list comprehensions in the 3rd edition of
'Learning Python' that recently arrived, as well as in 'Python in a
Nutshell, 2nd ed.' Then, with practice, I'll understand it well enough to
implement the multi-criteria target you illustrated.
Many 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
More information about the Portland
mailing list