You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python自定义类对象列表按属性排序失效问题求助

问题分析与解决

你没错误使用lambda表达式,问题出在**sorted()函数的特性**上:它不会直接修改原列表,而是返回一个全新的排序后的列表。你代码里只调用了sorted()但没把返回的新列表赋值给变量,所以原product_list完全没变化。

两种解决方法

方法1:接收sorted()的返回值

把排序后的新列表重新赋值给product_list,覆盖原列表:

product_list = sorted(product_list, key=lambda x: x.price)

方法2:使用列表的sort()方法

sort()是列表的原地排序方法,会直接修改原列表,不需要返回值:

product_list.sort(key=lambda x: x.price)

完整代码示例(以方法1为例)

class Product:
    def __init__(self,name,price,rating):
        self.name=name
        self.price=price
        self.rating=rating

product_list = [
Product("Laptop", 900, 4.5),
Product("Headphones", 100, 4.2),
Product("Keyboard", 50, 4.8),
Product("Monitor", 350, 4.6)
]

# 接收排序后的新列表
product_list = sorted(product_list, key=lambda x: x.price)
for product in product_list:
    print(product.name, product.price, product.rating)

两者的区别

  • sorted():生成新列表,原列表保持不变,适合需要保留原始数据的场景。
  • list.sort():直接修改原列表,不返回任何值(返回None),适合不需要保留原列表的场景。

内容的提问来源于stack exchange,提问作者user18051510

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 08:37:24