假设有以下数据:
collections = [
{'brand': 'Nike', 'profit': 1000, 'revenue': 2000},
{'brand': 'Adidas', 'profit': 2000, 'revenue': 4000},
{'brand': 'Puma', 'profit': 500, 'revenue': 1000},
{'brand': 'Under Armour', 'profit': 1500, 'revenue': 3000}
]
可以使用sorted()
函数进行排序,并传递一个排序函数作为其key
参数,该函数将返回每个品牌的利润百分比。
def sort_by_profit_percentage(item):
profit_percentage = (item['profit'] / item['revenue']) * 100
return profit_percentage
sorted_collections = sorted(collections, key=sort_by_profit_percentage, reverse=True)
for collection in sorted_collections:
print(collection)
输出结果为:
{'brand': 'Adidas', 'profit': 2000, 'revenue': 4000}
{'brand': 'Under Armour', 'profit': 1500, 'revenue': 3000}
{'brand': 'Nike', 'profit': 1000, 'revenue': 2000}
{'brand': 'Puma', 'profit': 500, 'revenue': 1000}
这意味着首先按品牌利润百分比从高到低排序,然后按降序排列结果集。
上一篇:按频率值排序数组项