2014-12-04 31 views
1

我有这样用行的文件:重排列表中的特定行

r1 1 10 
r2 10 1 #second bigger than third (10>1) 
r3 5 2 # ""  ""   (5>2) 
r4 10 20 

而且我想重新排序与所述第二字比第三大的线条,改变[3] possition到[2 ] possition。

所需的输出:

r1 1 10 
r2 1 10 
r3 2 5 
r4 10 20 

我已经作出重新排序行代码,但它只是重新排序线路输出,但并不是所有的线路:

with open('test','r') as file, open('reorderedtest','w')as out: 

for line in file: 
    splitLine = line.split("\t") 
    reorderedlist = [splitLine[0], splitLine[2], splitLine[1] ] 
    if int(splitLine[1]) > int(splitLine[2]): 
     str = " " 
     print str.join(reorderedlist) 

而且只打印:

r2 1 10 
r3 2 5 

任何想法来获得我想要的输出?

回答

2

到现有的代码最简单的修改是这样的:

with open('test','r') as file, open('reorderedtest','w')as out: 

for line in file: 
    splitLine = line.split("\t") 
    reorderedlist = [splitLine[0], splitLine[2], splitLine[1] ] 
    if int(splitLine[6]) > int(splitLine[7]): 
     str = " " 
     print str.join(reorderedlist) 
    else: 
     print line 
1

这将为任意数量的列,在那里你在第一列具有r#的工作,那么任何数量的数字列如下。

with open('test.txt') as fIn, open('out.txt', 'w') as fOut: 
    for line in fIn: 
     data = line.split() 
     first = data[0] # r value 
     values = sorted(map(int, data[1:])) # sorts based on numeric value 
     fOut.write('{} {}\n'.format(first, ' '.join(str(i) for i in values)) # write values back out 

所得out.txt文件

r1 1 10 
r2 1 10 
r3 2 5 
r4 10 20