I have some trouble making a code that arranges a .txt file in numerical order.
The problem I'm having is when ordering numbers 77, 45, 85, 100
in the .txt file it orders it as 100, 45, 77, 85
; 100 being the lowest.
Not sure how I would correct that as I want 100 to be the highest.
This is what I have so far:
import csv
import operator
sample = open("score.txt")
csv1 = csv.reader(sample, delimiter=',')
sort = sorted(csv1, key=operator.itemgetter(1))
for eachline in sort:
print eachline
Like budder says, try to convert your elements to int
or float
. "It's sorting in an unexpected manner because they are strings." Assuming that you are working with integers you can change your key
in sorted()
func:
sort = sorted(csv1, key=lambda x: int(x[1]))