Referencing Items in a List of Tuples

John Machin sjmachin at lexicon.net
Sat Feb 24 21:22:32 EST 2007


On Feb 25, 1:01 pm, rshep... at nospam.appl-ecosys.com wrote:
>   While working with lists of tuples is probably very common, none of my
> five Python books or a Google search tell me how to refer to specific items
> in each tuple. I find references to sorting a list of tuples, but not
> extracting tuples based on their content.
>
>   In my case, I have a list of 9 tuples. Each tuple has 30 items. The first
> two items are 3-character strings, the remaining 28 itmes are floats.
>
>   I want to create a new list from each tuple. But, I want the selection of
> tuples, and their assignment to the new list, to be based on the values of
> the first two items in each tuple.
>
>   If I try, for example, writing:
>
> for item in mainlist:

item is one of your 30-element tuples, ...


>     if mainlist[item][0] == 'eco' and mainlist[item][1] == 'con':

so do this:

    if item[0] == 'eco' and item[1] == 'con':

>       ec.Append(mainlist[item][2:])

and

         ec.append(item[2:]) # note append, not Append

>
> python doesn't like a non-numeric index.

If nothing. Python doesn't like a non-numeric index, quite
irrespective of what you do :-)


>   I would really appreciate a pointer

Sorry, only nasty languages have pointers :-)

> so I can learn how to manipulate lists
> of tuples by referencing specific items in each tuple (string or float).

HTH,
John




More information about the Python-list mailing list