Python 漂亮的按多列排序

Python prettytable Sort by Multiple Columns

我正在使用 PrettyTable 以漂亮的 table 格式将数据打印到终端。 按单列顺序打印它非常容易。

from prettytable import PrettyTable

table = PrettyTable(["Name", "Grade"])
table.add_row(["Joe", 90])
table.add_row(["Sally", 100])
print table.get_string(sortby="Grade", reversesort=True)

>> Table with Sally on top, because her score is highest.

我的问题是我想对两列进行排序。在这个替代案例中,我想按年级打印,如果有平局则按字母顺序打印。

table = PrettyTable(["Name", "Grade"])
table.add_row(["Joe", 90])
table.add_row(["Sally", 100])
table.add_row(["Bill", 90])
print table.get_string(sortby=("Grade","Name"), reversesort=True)

>> Doesn't work

文档说 sort_key 将允许我编写一个函数来完成此操作,但我还没有看到实际的实现。

您可以调用 operator.itemgetter() 作为 sort_key 值。请注意,sortby 仍然需要为要应用的 sort_key 提供:

import operator
from prettytable import PrettyTable


table = PrettyTable(["Name", "Grade"])
table.add_row(["Joe", 90])
table.add_row(["Sally", 100])
table.add_row(["Bill", 90])
table.add_row(["Alice", 90])
print table.get_string(sort_key=operator.itemgetter(1, 0), sortby="Grade")

打印:

+-------+-------+
|  Name | Grade |
+-------+-------+
| Alice |   90  |
|  Bill |   90  |
|  Joe  |   90  |
| Sally |  100  |
+-------+-------+
from prettytable import PrettyTable
    
x = PrettyTable()
x.field_names = ["City name", "Area", "Population", "Annual Rainfall"]

x.add_row(["Adelaide", 1295, 1158259, 600.5])
x.add_row(["Brisbane", 5905, 1857594, 1146.4])
x.add_row(["Darwin", 112, 120900, 1714.7])
x.add_row(["Hobart", 1357, 205556, 619.5])
x.add_row(["Sydney", 2058, 4336374, 1214.8])
x.add_row(["Melbourne", 1566, 3806092, 646.9])
x.add_row(["Perth", 5386, 1554769, 869.4])

print("Table sorted by population:")
x.sortby = "Population"
print(x)

来源:https://zetcode.com/python/prettytable/