[Tutor] Flatten a list in tuples and remove doubles

Prasad, Ramit ramit.prasad at jpmorgan.com
Thu Jul 19 20:09:03 CEST 2012


> I would get a new list as:
> 
> [(0, '3eA', 'Dupont', 'Juliette', '11.0/10.0', '4.0/5.0', '17.5/30.0',
> '3.0/5.0', '4.5/10.0', '35.5/60.0'), (1, '3eA', 'Pop', 'Iggy',
> '12.0/10.0', '3.5/5.0', '11.5/30.0', '4.0/5.0', '5.5/10.0',
> '7.5/10.0', '40.5/60.0')]
> 
> ... from this one:
> 
> [(0, '3eA', 'Dupont', 'Juliette', 0, 11.0, 10.0), (0, '3eA', 'Dupont',
> 'Juliette', 1, 4.0, 5.0), (0, '3eA', 'Dupont', 'Juliette', 2, 17.5,
> 30.0), (0, '3eA', 'Dupont', 'Juliette', 3, 3.0, 5.0), (0, '3eA',
> 'Dupont', 'Juliette', 4, 4.5, 10.0), (0, '3eA', 'Dupont', 'Juliette',
> 5, 35.5, 60.0), (1, '3eA', 'Pop', 'Iggy', 0, 12.0, 10.0), (1, '3eA',
> 'Pop', 'Iggy', 1, 3.5, 5.0), (1, '3eA', 'Pop', 'Iggy', 2, 11.5, 30.0),
> (1, '3eA', 'Pop', 'Iggy', 3, 4.0, 5.0), (1, '3eA', 'Pop', 'Iggy', 4,
> 5.5, 10.0), (1, '3eA', 'Pop', 'Iggy', 5, 40.5, 60.0)]
> 
> How to make that ? I'm looking for but for now I can't do it.


Well first thing to do would be to describe the logic behind what
you are doing. Without knowing that it is difficult to come up
with the correct solution. I am guessing you want a list
where fields 1,2,3 (based on the first element being field 0) 
of field a string of `field 5 + '/' + field 6`. But that does
not tell me what field 0 should be in the new format.

This is a pretty crude sample that should work for you.

lookup = {}

for row in old_list:
    key = (row[1],row[2],row[3])
    field_0, ratios = lookup.setdefault( key, (row[0], []) )
    ratios.append( '{0}/{1}'.format( row[5], row[6] ) )
new_list = []
for key, value in lookup.items():
    row = [ value[0], key[0], key[1], key[2] ]
    row.extend(value[1])
    new_list.append(tuple(row))

# Might need to sort to get the exact same results


Ramit

This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  


More information about the Tutor mailing list