【问题标题】:Organising two column data组织两列数据
【发布时间】:2012-07-17 09:53:21
【问题描述】:

您好,我有一个两列数据存储在一个名为“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 

任何帮助将不胜感激

【问题讨论】:

  • 必须是 Python 吗? sort -n Cv_0.out
  • 在您当前的代码中究竟是什么不工作?您能否指出当前输出的外观?

标签: python sorting csv


【解决方案1】:

即使没有 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]。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-12
    • 1970-01-01
    • 2013-12-14
    • 1970-01-01
    • 2011-07-17
    • 1970-01-01
    • 2017-01-17
    • 1970-01-01
    相关资源
    最近更新 更多