2014-03-12 51 views
0

在這個文件中,我有兩列,其中Ist列描述浮點時間,第二列表示字符串。基於Ist列對文件進行排序並同時修改文件中的第2列

<time> <str> 
8.45 A 
6.12 B 
10.12 C 
1.45 D 
2.12 E 
0.45 F 
.... 
... 
.. 

我想根據第一列和輸出應該是這樣的文件排序:

0.45 F 
1.45 D 
2.12 E 
6.12 B 
8.45 A 
10.12 C 

請幫我解決這個做法是:我把每列兩列出每個。我正在用float數對數組進行排序,並同時進行必要的調整。

+1

我沒有看到「同時修改第二列」的一部分。 – kojiro

回答

1
with open('filename.txt', 'w') as fout: 
    for line in sorted(open('filename.txt', 'r').readlines(), key=lambda x:float(x.split()[0])): 
     fout.write(line) 
0
li = ['Do you know how to read a file ?', 
     'Do you know how to split a string into a list ?', 
     'Do you know how to sort a list ?', 
     'Do you know how to join string elements of a list ?', 
     'Do you know how to write in a file ?'] 

def your_answer(e): 
    y = 'go' 
    while y not in ('yes','no'): 
     y = raw_input('%s\nenter yes or no :' % e) 
    return y 

if any(your_answer(e)=='no' for e in li): 
    print 'Please, read the documentations.' 
else: 
    print 'Show what you tried.' 
相關問題