user1532014
user1532014

Reputation: 31

Organising two column data

Hi I have a two column data stored in a file called "Cv_0.out", each column is separated by two spaces

12  454
232  123
879  2354 
12312  23423
8794  1237
3245  34

I would like to then sort this data in ascending order based only on the right hand column values whilst at the same time keeping the pairs of values together, so reordering the left hand side values. I would like to get the following:

3245  34
232  123
12  454
8794  1237
879  2354
12312  23423

I have tried the following so far:

import sys,csv    
import operator
reader = csv.reader(open('Cv_0.out'),delimiter=' ')
sort = sorted(reader, key=lambda row: int(row[0]))
print sort 

Any help would be really appreciated

Upvotes: 3

Views: 107

Answers (1)

UltraInstinct
UltraInstinct

Reputation: 44444

Your input file can be dealt even without CSV:

with open("input") as f:
    lines = (map(int,x.strip().split()) for x in f)
    newLines = sorted(lines, key=lambda row: row[1])
    print "\n".join(str(x)+ " " + str(y)  for x,y in newLines)

IMO, the problem was using row[0] instead of row[1], if you wanted to sort on the second column.

Upvotes: 2

Related Questions