0

Here's my full code sample:

import csv
import operator

f=open('C://Users//ganesha//Desktop//b//sampleDataCsv.csv',"r")
readerObject1 = csv.reader(f,delimiter = ",")    
inputList = list(readerObject1)    
print("Input",inputList)

sortedList = sorted(inputList,key=operator.itemgetter(0),reverse=True)

print("Output",sortedList)

f1=open('C://Users//ganesha//Desktop//b//sampleDataCsv4.csv',"w+") 
writerObject=csv.writer(f1,delimiter=",",lineterminator='\n')

writerObject.writerows(sortedList)

My input looks like this:

[['20'], ['12'], ['13'], ['11'], ['14'], ['15'], ['19'], ['1'], ['2'], ['4'], ['9'], ['0'], ['8'], ['7'], ['5'], ['6'], ['3'], ['16'], ['17'], ['10']]

And my output comes out like this:

[['9'], ['8'], ['7'], ['6'], ['5'], ['4'], ['3'], ['20'], ['2'], ['19'], ['17'], ['16'], ['15'], ['14'], ['13'], ['12'], ['11'], ['10'], ['1'], ['0']]
Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
shane
  • 75
  • 1
  • 1
  • 4

1 Answers1

3

Well, that's because you're sorting strs that represent the numbers. Create a small lambda that gets the item and casts it to int to get a sort based on int values:

k = lambda x: int(x[0])    
sortedList = sorted(inputList,key=k,reverse=True)

Now sortedList is sorted based on the int values:

[['20'], ['19'], ['17'], ['16'], ['15'], ['14'], ['13'], ['12'],
 ['11'], ['10'], ['9'], ['8'], ['7'], ['6'], ['5'], ['4'], ['3'],
 ['2'], ['1'], ['0']]

If you don't mind some convolution, place the lambda directly in the call to sorted:

sortedList = sorted(inputList, key=lambda x: int(x[0]), reverse=True)
Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253