用write对python创建的list文件进行排序



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

我尝试了这个和元组的例子,但它们的输出是

['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()

请帮我把文件整理好。

您发现的问题是字符串按字母顺序排序,而不是按数字排序。您需要做的是将每个项从字符串转换为浮点,对浮点列表进行排序,然后再次输出为字符串。

我在这里重新创建了你的文件,所以你可以看到我是直接从文件中读取的。

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:,因为它自动处理所有的打开和关闭。更安全的记忆。

最新更新