[portland] Indexing Lists of Tuples
hallettj at gmail.com
Sat Sep 29 03:18:56 CEST 2007
I just did some experimenting with your example. I was able to get at
the element in question with L, just as you suggested. The only
change I mad was to add a comma between the tuples that was probably
left out when you pasted in the example.
I'm using Python version 2.5.1, in case that makes any difference.
On 9/28/07, Rich Shepard <rshepard at appl-ecosys.com> wrote:
> 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, 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 ?
> 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.
> 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
> Portland mailing list
> Portland at python.org
More information about the Portland