[portland] Indexing Lists of Tuples
Rich Shepard
rshepard at appl-ecosys.com
Sat Sep 29 03:04:43 CEST 2007
For some reason, I cannot find the answer to what I assumed to be a
trivially simple question: given a list of tuples, how do I reference items
within a given tuple?
Looking at "Byte of Python," "Dive Into Python," and "Learning Python" the
explanations of lists and tuples deal with the equivalent of a 1-dimensional
array. The only reference to multiple indices, e.g., L[1][0], note that this
is the fist element of the second item in the list. My experiments on my
data bear this out.
In my situation, I have rows retrieved from database tables and stored in
variables as lists of tuples. For example:
[(u'Low', u'HabitatComplexity', u'Terrestrial', u'Wildlife', u'Decay
S-Curve', 1, 0.0, 1.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0, 1.0)
(u'High', u'HabitatComplexity', u'Terrestrial', u'Wildlife', u'Growth
S-Curve', 2, 0.0, 1.0, 0.0, 0.5, 0.0, 1.0, 0.5, 0.5, 1.0, 1.0)]
I would like to extract the tuple where element 5 == 2; in this example,
the second tuple in the list. Is there a way to directly reference tuple 1, item 5
as one would in C as [1][5]?
The best I've come up with is to search for the tuple with elements I
want, then append them to a new list. Now I have a list with only one set of
elements and I can index them directly.
Spent too much time today beating my head against the wall, trying to
learn how to address specific elements in lists of tuples. Can it be done?
If so, please teach me how.
TIA,
Rich
--
Richard B. Shepard, Ph.D. | The Environmental Permitting
Applied Ecosystem Services, Inc. | Accelerators(TM)
<http://www.appl-ecosys.com> Voice: 503-667-4517 Fax: 503-667-8863
More information about the Portland
mailing list