我在根据Python中自定义类对象的一个属性对其进行排序时遇到了一个问题.我有一个Product对象列表(如下所示自己创建了这个类),每个对象都有名称、价格和评级属性.我正试着按价格属性升序对列表进行排序.
这是我从另一个问题中找到的key=lambda x: x.price
的代码
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)
]
sorted(product_list, key=lambda x: x.price)
for product in product_list:
print(product.name, product.price, product.rating)
然而,这段代码似乎不会对列表进行排序--它仍然是按原始顺序排列的.奇怪的是,我没有收到任何错误,所以我找不到错误在哪里.
有没有人能帮我了解一下发生了什么事?我在这个上下文中错误地使用了排序函数和lambda
吗?抱歉,如果这是个低级的问题.