1

I have file containing data like:

12, 9
13, 9  
45, 23
1, 4 
0, 8
91, 45
638, 56
123, 3  
2, 9

now what I need to do is sort it like:

0, 8
1, 4
2, 9
12, 9
13, 9
45, 23
91, 45
123, 3
638, 56

I have tried using:

import sys,csv    
import operator
reader = csv.reader(open('filename.txt'),delimiter=',')
sort = sorted(reader,key=operator.itemgetter(0),reverse=False)

but this is not working for me. It arranging the column based on the 1st location not arranging as I wanted.i.e. :

0, 8
1, 4
12, 9
123, 3
13, 9
2, 9
45, 23
638, 56
91, 45

please help.

eumiro
  • 207,213
  • 34
  • 299
  • 261
diffracteD
  • 758
  • 3
  • 10
  • 32

3 Answers3

5
sorted(reader, key=lambda row: int(row[0]))
San4ez
  • 8,091
  • 4
  • 41
  • 62
  • @San4ez thanx for you help. Would you please tell me is it possible to draw a hitogram from this data using a class interval of 10. thank you. – diffracteD May 10 '12 at 10:54
  • @abhisek can you use excel for this purpose? Although it's better to ask another question – San4ez May 10 '12 at 12:17
0

I believe the result you are getting when applying the solution you describe is just as expected. All that is left is that you need to cast first column to integers instead of using the string values(as otherwise you will get lexicographical sort):

import sys,csv
import operator
reader = csv.reader(open('filename.txt'),delimiter=',')
sort = sorted(reader,key=lambda row: int(row[0]),reverse=False)
Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176
0

I think you are sorting strings there. How about:

sort = sorted(tuple(int(x) for x in row) for row in reader)
uhz
  • 2,468
  • 1
  • 20
  • 20