2012-07-18 44 views
3

您好我有存储在一个名为“Cv_0.out”文件的两个数据,每列由两个空间组织两个栏数据

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

我想,然后以升序排序该数据仅基于右侧列值,同时将值对保持在一起,从而重新排序左侧值。我想获得如下:到目前为止以下

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

我曾尝试:

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

任何帮助将非常感激

+1

它是否必须是Python? 'sort -n Cv_0.out' – eumiro 2012-07-18 11:27:55

+1

什么是不正确的工作在你当前的代码?你能否指出目前的输出结果如何? – Paranaix 2012-07-18 11:30:12

回答

2

输入文件即使不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,问题是使用row[0]而不是row[1],如果你想在第二列进行排序。