2014-12-04 35 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