Texttable输出:
Label1 | String | Count
-------------------------------------------------------------------------
Addr[24]: | "Akjalfj " | 15
Addr[25]: | "laflklk" | 16
Addr[26]: | "amfalkj" | 13
Addr[27]: | "asflklal" | 21
我想根据计数值按降序排序上面的texttable输出
Addr[27]: | "asflklal" | 21
应出现在第一行。我如何在Python中实现这一目标?
答案 0 :(得分:0)
如果由于某种原因无法在添加行之前对行进行排序,则可以将其读入并排序,然后写入另一个文件:
with open('in.txt', 'r') as f,open('output.txt','w') as f1:
lines = f.readlines()
updated = sorted(lines[2:],key = lambda x: int(x.strip()[-3:]),reverse=True)
for line in lines[0:2]:
f1.write(line)
for line in updated:
f1.write("{}\n".format(line.strip()))
此输出仅在所有行的格式与示例相同时才有效:
Label1 | String | Count
-------------------------------------------------------------------------
Addr[27]: | "asflklal" | 21
Addr[25]: | "laflklk" | 16
Addr[24]: | "Akjalfj " | 15
Addr[26]: | "amfalkj" | 13