面试题答案
一键面试class CustomClass:
def __init__(self, weight, volume):
self.weight = weight
self.volume = volume
big_list = [CustomClass(1.5, 2.0), CustomClass(1.5, 1.0), CustomClass(2.0, 3.0)]
sorted_list = sorted(big_list, key=lambda x: (-x.weight, x.volume))
性能优化措施及原因
- 在
key
函数中直接返回元组:通过直接在key
函数中返回(-x.weight, x.volume)
这样的元组,利用Python内置的元组比较机制。Python会按照元组元素的顺序依次比较,所以这种方式简洁高效,避免了额外的比较逻辑实现。 - 使用负号处理反向排序:对于
weight
按从大到小排序,通过取-x.weight
,这样在比较时就相当于对weight
进行了反向排序,而无需自己实现复杂的反向比较逻辑,减少了计算量,提升了性能。