使用write对python创建的列表文件进行排序

时间:2015-02-11 14:01:11

标签: sorting python-3.x

我有一个由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()

请帮我正确整理文件。

1 个答案:

答案 0 :(得分: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:,因为它会自动处理所有打开和关闭。更安全的内存。