网上的教程,多数如下,但排序不起作用:
from prettytable import PrettyTable
table = PrettyTable(["animal", "ferocity"])
table.add_row(["wolverine", 100])
table.add_row(["grizzly", 87])
table.add_row(["Rabbit of Caerbannog", 110])
table.add_row(["cat", -1])
table.add_row(["platypus", 23])
table.add_row(["dolphin", 63])
table.add_row(["albatross", 44])
table.sort_key("ferocity")
table.reversesort = True
print(table)
输出
+----------------------+----------+
| animal | ferocity |
+----------------------+----------+
| wolverine | 100 |
| grizzly | 87 |
| Rabbit of Caerbannog | 110 |
| cat | -1 |
| platypus | 23 |
| dolphin | 63 |
| albatross | 44 |
+----------------------+----------+
修正如下:
from prettytable import PrettyTable
table = PrettyTable(["animal", "ferocity"])
table.add_row(["wolverine", 100])
table.add_row(["grizzly", 87])
table.add_row(["Rabbit of Caerbannog", 110])
table.add_row(["cat", -1])
table.add_row(["platypus", 23])
table.add_row(["dolphin", 63])
table.add_row(["albatross", 44])
# table.sort_key("ferocity")
# table.reversesort = True
# print(table)
print(table.get_string(sortby="ferocity", reversesort=True))
输出
+----------------------+----------+
| animal | ferocity |
+----------------------+----------+
| Rabbit of Caerbannog | 110 |
| wolverine | 100 |
| grizzly | 87 |
| dolphin | 63 |
| albatross | 44 |
| platypus | 23 |
| cat | -1 |
+----------------------+----------+