I am attempting to sort my csv file by a specific column. That is easy enough with this below code:
with open("outfile.csv","rb") as infile,open("outfile.csv","wb") as outfile:
reader= csv.reader(infile,delimiter=',')
writer= csv.writer(outfile)
sort= sorted(reader,key=operator.itemgetter(7), reverse= True)
for eachline in sort:
writer.writerow(eachline)
In my example however, it will sort but will sort in an odd way. For example, it would return the file to me descending in this order: 3.8,3.7,3.1,21.7,21.6,2.8.
Since this is causing me an issue, I would like to fix this; if it can't, instead I'd like to sort by largest length if that is possible.
This sounds confusing but this is the issue I am having. Any help would be great.
Thank you.
尝试对float
值而不是str
值进行排序:
sort= sorted(reader,key=lambda x:float(x[7]), reverse= True)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.