过去两天我一直在努力解决这个问题,但我无法解决。
我有一份字典列表,需要打印成表格,员工需要根据出售的房产数量从高到低进行排名。
import tabulate
data_list = [
{
'Name': 'John Employee',
'Employee ID': 12345,
'Properties Sold': 5,
'Commission': 2500,
'Bonus to Commission': 0,
'Total Commission': 2500
},
{
'Name': 'Allie Employee',
'Employee ID': 54321,
'Properties Sold': 3,
'Commission': 1500,
'Bonus to Commission': 0,
'Total Commission': 1500
},
{
'Name': 'James Employee',
'Employee ID': 23154,
'Properties Sold': 7,
'Commission': 3500,
'Bonus to Commission': 525,
'Total Commission': 4025
}
]
header = data_list[0].keys()
rows = [x.values() for x in data_list]
print(tabulate.tabulate(rows, header))
输出:
Name Employee ID Properties Sold Commission Bonus to Commission Total Commission
-------------- ------------- ----------------- ------------ --------------------- ------------------
John Employee 12345 5 2500 0 2500
Allie Employee 54321 3 1500 0 1500
James Employee 23154 7 3500 525 4025
所需输出:
Name Employee ID Properties Sold Commission Bonus to Commission Total Commission
-------------- ------------- ----------------- ------------ --------------------- ------------------
James Employee 23154 7 3500 525 4025
John Employee 12345 5 2500 0 2500
Allie Employee 54321 3 1500 0 1500
您可以根据出售的属性对字典列表进行排序:
sorted_data_list = sorted(data_list, key=lambda x: x["Properties Sold"], reverse=True)
header = sorted_data_list[0].keys()
rows = [x.values() for x in sorted_data_list]
print(tabulate.tabulate(rows, header))
从未使用过tabulate
,我可以建议在pandas
中使用解决方案
df = pd.DataFrame.from_records(data_list).sort_values(by='Properties Sold', ascending=False)