如何正确排序 Python 的 PrettyTable 整数列
How to sort Python's PrettyTable integer column correctly
我们在对 Population
列进行排序时遇到问题。问题是
PrettyTable 将 CSV 文件中的所有数据作为字符串读取,并将整数值作为字符串进行排序。如何解决这个问题?
#!/usr/bin/python3
from prettytable import from_csv
with open("data.csv", "r") as fp:
x = from_csv(fp)
x.sortby = "Population"
print(x)
data.csv
"City name", "Area", "Population", "Annual Rainfall"
"Adelaide", 1295,1158259, 600.5
"Brisbane", 5905,1857594, 1146.4
"Darwin", 11200000,120900, 1714.7
"Hobart", 1357,205556, 619.5
"Sydney", 2058,4336374, 1214.8
"Melbourne", 1566,3806092, 646.9
"Perth", 5386,1554769, 869.4
您可以使用 sort_key
参数来实现,其中自定义键函数被传递给:
#!/usr/bin/python3
from prettytable import from_csv
with open("data.csv", "r") as fp:
x = from_csv(fp)
print(x.get_string(sortby='Population', sort_key=lambda row: int(row[0])))
输出:
+-----------+----------+------------+-----------------+
| City name | Area | Population | Annual Rainfall |
+-----------+----------+------------+-----------------+
| Darwin | 11200000 | 120900 | 1714.7 |
| Hobart | 1357 | 205556 | 619.5 |
| Adelaide | 1295 | 1158259 | 600.5 |
| Perth | 5386 | 1554769 | 869.4 |
| Brisbane | 5905 | 1857594 | 1146.4 |
| Melbourne | 1566 | 3806092 | 646.9 |
| Sydney | 2058 | 4336374 | 1214.8 |
+-----------+----------+------------+-----------------+
我们在对 Population
列进行排序时遇到问题。问题是
PrettyTable 将 CSV 文件中的所有数据作为字符串读取,并将整数值作为字符串进行排序。如何解决这个问题?
#!/usr/bin/python3
from prettytable import from_csv
with open("data.csv", "r") as fp:
x = from_csv(fp)
x.sortby = "Population"
print(x)
data.csv
"City name", "Area", "Population", "Annual Rainfall"
"Adelaide", 1295,1158259, 600.5
"Brisbane", 5905,1857594, 1146.4
"Darwin", 11200000,120900, 1714.7
"Hobart", 1357,205556, 619.5
"Sydney", 2058,4336374, 1214.8
"Melbourne", 1566,3806092, 646.9
"Perth", 5386,1554769, 869.4
您可以使用 sort_key
参数来实现,其中自定义键函数被传递给:
#!/usr/bin/python3
from prettytable import from_csv
with open("data.csv", "r") as fp:
x = from_csv(fp)
print(x.get_string(sortby='Population', sort_key=lambda row: int(row[0])))
输出:
+-----------+----------+------------+-----------------+
| City name | Area | Population | Annual Rainfall |
+-----------+----------+------------+-----------------+
| Darwin | 11200000 | 120900 | 1714.7 |
| Hobart | 1357 | 205556 | 619.5 |
| Adelaide | 1295 | 1158259 | 600.5 |
| Perth | 5386 | 1554769 | 869.4 |
| Brisbane | 5905 | 1857594 | 1146.4 |
| Melbourne | 1566 | 3806092 | 646.9 |
| Sydney | 2058 | 4336374 | 1214.8 |
+-----------+----------+------------+-----------------+