diffracteD
diffracteD

Reputation: 758

how to sort data from a file having two columns in python

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.

Upvotes: 1

Views: 2528

Answers (3)

uhz
uhz

Reputation: 2518

I think you are sorting strings there. How about:

sort = sorted(tuple(int(x) for x in row) for row in reader)

Upvotes: 0

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70939

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)

Upvotes: 0

San4ez
San4ez

Reputation: 8241

sorted(reader, key=lambda row: int(row[0]))

Upvotes: 5

Related Questions