2013-06-04 54 views
1

所以我在文件中的下列输出(千行) input.txt中上的行排序号升序排列

2956:1 1076:1 4118:1 1378:1 2561:1 
1039:1 1662:1 
1948:1 894:1 1797:1 1662:1 

问题是我必须按升序编号

排序每一行

所需的输出: output.txt的

1076:1 1378:1 2561:1 2956:1 4118:1 
1039:1 1662:1 
894:1 1662:1 1797:1 1948:1 

这已成为一个真正的挑战,得到它的权利,即时寻找一个Python函数d这对我来说。这些行必须保持它们的顺序,但每行必须按升序排序(就像输出一样)。

有关如何做到这一点的任何想法?

回答

11
with open('input.txt') as f, open('output.txt', 'w') as out: 
    for line in f: 
     line = line.split() #splits the line on whitespaces and returns a list 
     #sort the list based on the integer value of the item on the left side of the `:` 
     line.sort(key = lambda x: int(x.split(':')[0])) 
     out.write(" ".join(line) + '\n') 

输出:

1076:1 1378:1 2561:1 2956:1 4118:1 
1039:1 1662:1 
894:1 1662:1 1797:1 1948:1 
+1

Python的答案,为什么会出现这么多的爱;-) – iruvar

+0

@Ashwini乔杜里........... 1个问题,我怎么确保它每行删除双打?没有从文件双打,只是不允许有双打线.... svm软件不喜欢它:P –

+0

@ RHK-S8双打是什么意思? –

2

不确定蟒,但一般来说,我会采取每一行作为“记录”,然后“爆炸”行到由分隔阵列空间(或正则表达式的一组空格或制表符,或任何分隔符),然后一个简单的数组排序,然后“内爆”回到一个字符串。

我的“引号”等价于PHP函数。

1

一种方式来做到这一点是这样的:

def sort_input(input_file): 
    for line in input_file: 
    nums = line.strip().split() 
    nums.sort(key=lambda x: int(x.split(':')[0])) 
    print ' '.join(nums)