I have a variable compareout
that stores nested lists of data:
compareout = [...
[Guyana,951.723423,1037.123424,28.476757,2.991234],
[Bolivia,936.123420,1065.8234236,43.25123,4.62],
[Philippines,925.52342342,1119.62342341,64.70234234,6.991234123],
[Congo (Rep.),907.22342343,1657.52342349,250.1242342,27.571234123],
...]
I'm trying to:
- Sort by the second column ascending, write the first 10 items of this sorted list to a .csv
- Sort by the second column descending, write this first 10 items sorted list to a second .csv
However, I need to format the output so that all the floats are only 2 decimal places, and contcatenate USD to front of the second and third column values, and add a '%' sign to the end of the final column value. While I can iterate over 'compareout' and replace the last two colums like so...
for line in compareout:
avgyrincr = (float(line[2])-float(line[1]))/3
percent = (avgyrincr/float(line[1])) * 100
line.append("%.2f" % avgyrincr)
line.append("%.2f%%" % percent)
I can't do something simple like:
for line in ascending:
line[1] = "USD %.2f" % line[1]
line[2] = "USD %.2f" % line[2]
because this does not allow sorting. Currently I have the immediately above code occurring after I sort and write the data the first time to the first file, but of course I cannot then sort by descending...also I'm confused as to how to specify writing 10 items only...
I have googled for about an hour and can't seem to find enough information as to whether the csv.writerow() function allows formatting while writing, and I've run out of approaches. If someone could give me some ideas I would be most appreciative...