2015-02-11 54 views
0

我使用python3創建的文件:排序由蟒蛇與寫創建的文件列表

of.write("{:<6f} {:<10f} {:<18f} {:<10f}\n" 
        .format((betah), test, (torque*13605.698066), (mom))) 

輸出文件看起來像:

$cat pout 
15.0  47.13 0.0594315908872 0.933333333334 
25.0  29.07 0.143582198404  0.96  
20.0  35.95 0.220373446813  0.95  
5.0  124.12 0.230837577743  0.800090803982 
4.0  146.71 0.239706979471  0.750671150402 
0.5  263.24 0.239785533064  0.163953413739 
1.0  250.20 0.240498520899  0.313035285499 

現在,我要對列表進行排序。

整理的預期產出將是:

25.0  29.07 0.143582198404  0.96  
20.0  35.95 0.220373446813  0.95 
15.0  47.13 0.0594315908872 0.933333333334 
5.0  124.12 0.230837577743  0.800090803982 
4.0  146.71 0.239706979471  0.750671150402 
1.0  250.20 0.240498520899  0.313035285499 
0.5  263.24 0.239785533064  0.163953413739 

我試圖this和元組例如this但它們產生的輸出作爲

['0.500000 263.240000 0.239786   0.163953 \n', '15.000000 47.130000 0.059432   0.933333 \n', '1.000000 250.200000 0.240499   0.313035 \n', '25.000000 29.070000 0.143582   0.960000 \n', '20.000000 35.950000 0.220373   0.950000 \n', '4.000000 146.710000 0.239707   0.750671 \n', '5.000000 124.120000 0.230838   0.800091 \n'] 

,不要嘗試匹配輸入和輸出的數量,因爲它們都是爲了簡潔而被截斷的。

至於我自己嘗試從1的幫助排序的例子是這樣的:

f = open("tmp", "r") 
lines = [line for line in f if line.strip()] 
print(lines) 
f.close() 

請幫助我正確地對文件進行排序。

+0

'help(sorted)'和'import operator;幫助(operator.itemgetter)'是很好的開始。 – twalberg 2015-02-11 14:52:57

回答

0

您發現的問題是字符串按字母順序排序而不是數字排序。你需要做的是將每個項目從一個字符串轉換爲一個浮點數,對浮點數列表進行排序,然後再次輸出爲一個字符串。

我在這裏重新創建了你的文件,所以你可以看到我直接從文件中讀取。

pout = [ 
"15.0  47.13 0.0594315908872 0.933333333334", 
"25.0  29.07 0.143582198404  0.96   ", 
"20.0  35.95 0.220373446813  0.95   ", 
"5.0  124.12 0.230837577743  0.800090803982", 
"4.0  146.71 0.239706979471  0.750671150402", 
"0.5  263.24 0.239785533064  0.163953413739", 
"1.0  250.20 0.240498520899  0.313035285499"] 

with open('test.txt', 'w') as thefile: 
    for item in pout: 
     thefile.write(str("{}\n".format(item))) 

# Read in the file, stripping each line 
lines = [line.strip() for line in open('test.txt')] 
acc = [] 
# Loop through the list of lines, splitting the numbers at the whitespace 
for strings in lines: 
    words = strings.split() 
    # Convert each item to a float 
    words = [float(word) for word in words] 
    acc.append(words) 
# Sort the new list, reversing because you want highest numbers first 
lines = sorted(acc, reverse=True) 
# Save it to the file. 
with open('test.txt', 'w') as thefile: 
    for item in lines: 
     thefile.write("{:<6} {:<10} {:<18} {:<10}\n".format(item[0], item[1], item[2], item[3])) 

另外請注意,我用with open('test.txt', 'w') as thefile:因爲它會自動處理所有的開閉。更多的內存安全。