Python:按列值对texttable进行排序

时间:2014-07-11 22:03:28

标签: python python-2.7

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中实现这一目标?

1 个答案:

答案 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