4

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
peterh
  • 11,875
  • 18
  • 85
  • 108
B_lo
  • 29
  • 1
  • 5
  • 1
    I think you need to convert the text to a float or integer. It's sorting in an unexpected manner because they are strings. – bud Sep 28 '15 at 23:15
  • Can you post a small sample of the csv file ? – Pedro Lobito Sep 28 '15 at 23:16
  • You need to clarify a bit. Are you sorting a bunch of integers? Or is it things that look like this: bar3, bar15xyz, bar 32, foo1, foo2, foo10, foo23, foo103. If the latter, what you want is a natural order sort. – cbare Sep 28 '15 at 23:21
  • For a rant on natural order sort and a quick Python implementation, see: http://blog.codinghorror.com/sorting-for-humans-natural-sort-order/ – cbare Sep 28 '15 at 23:24

3 Answers3

4

Like budder says, try to convert your elements to int or float. Assuming that your are working with integers you can change your key in sorted() func:

sort = sorted(csv1, key=lambda x : int(x[1]))
Robin Curbelo
  • 1,323
  • 1
  • 11
  • 21
1

You need to sort them numerically instead of alphabetically.

Try this:

sort = sorted(csv1, key=lambda item: int(item[1]))
eugenioy
  • 11,825
  • 28
  • 35
1

The entries need to first be converted to integers to be correctly sorted.

score.txt

312
148
17
108

python

with open('score.txt', 'r') as f:
    lines = f.readlines()
numbers = [int(e.strip()) for e in lines]
numbers.sort()
print numbers

#[17, 108, 148, 312]
Martin Evans
  • 45,791
  • 17
  • 81
  • 97
Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268