user1532369
user1532369

Reputation: 179

Exporting a modified list to CSV

I have a large list, contains a series of ids and related values, extremely shortened version looks like so:

large = [('5501', [(4, 5, 8), (6, -4, -6)]), ('2222', [(2, 4, -5), (1, -15, 4)])]

My goal is to export a modified version of 'large' (with additions) to Excel (every value with its own separate cell - i.e. 5501 being in A1, 4 in A2, 5 in B2, 8 in C2... the first space would be in A4 etc.) which look like this:

DESIRED FORM OUTPUTTED TO EXCEL

5501 
4,5,8 
6,-4,-6
'space here'
'Sorted absolutes maxes'
8, 6, 5
'space here'     
2222 
2,4,-5 
1,-15,4
'space here'
'Sorted absolutes maxes'
15, 5, 2
'space here' 

I have been able to export the above desired form using the following code:

import csv
with open("out1.csv", "wb") as fp: 
   writer = csv.writer(fp, delimiter=",")     
   for entry in large:        
       writer.writerow([entry[0]])         
       for line in entry[1]:             
           writer.writerow(line)        
       writer.writerow([])

However it does not have the required sorted absolute (i.e. neglecting any '-' signs) maxes like in the desired form above included. This is where I need help - help much appreciated.

Upvotes: 0

Views: 205

Answers (1)

Michael Mauderer
Michael Mauderer

Reputation: 3882

First you can get the absolute values by mapping your tuples with the abs like this

map(abs, entry[1][0]) 
map(abs, entry[1][1]) 

You can then get the pairwise maxima by first using zip to create the positional pairs

zip(map(abs, entry[1][0]), map(abs, entry[1][1]))

and then again mapping these pairs to their respective maxima:

map(max, zip(map(abs, entry[1][0]), map(abs, entry[1][1])))

Now all you have to do is sort them from max to min and write them to your file:

with open("out1.csv", "wb") as fp: 
   writer = csv.writer(fp, delimiter=",")     
   for entry in large:        
       writer.writerow([entry[0]])         
       for line in entry[1]:             
           writer.writerow(line)        
       writer.writerow([])
       writer.writerow(['Sorted absolute maxes'])
       maxima = map(max, zip(map(abs, entry[1][0]), map(abs, entry[1][1])) )
       writer.writerow(sorted(maxima, reverse=True))
       writer.writerow([])

This gives me the following output:

5501
4,5,8
6,-4,-6

Sorted absolute maxes
8,6,5

2222
2,4,-5
1,-15,4

Sorted absolute maxes
15,5,2

Upvotes: 2

Related Questions