Referencing Items in a List of Tuples

Jussi Salmela tiedon_jano at hotmail.com
Sun Feb 25 12:44:06 EST 2007


Paddy kirjoitti:
> On Feb 25, 2:01 am, 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:
>>     if mainlist[item][0] == 'eco' and mainlist[item][1] == 'con':
>>       ec.Append(mainlist[item][2:])
>>
>> python doesn't like a non-numeric index.
>>
>>   I would really appreciate a pointer so I can learn how to manipulate lists
>> of tuples by referencing specific items in each tuple (string or float).
>>
>> Rich
> 
> You might also use list comprehensions to accumulate the values you
> need:
> 
> ec = [ item[2:]  for item in mainlist  if item[:2] == ['eco','con'] ]
> 
> - Paddy.
> 

I'm nitpicking, but the OP has a list of tuples:

ec = [ item[2:]  for item in mainlist  if item[:2] == ('eco','con') ]


Cheers,
Jussi



More information about the Python-list mailing list