以下是一个示例代码,演示了如何按照价格从低到高对一个对象数组进行排序:
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
def __repr__(self):
return f"{self.name}: {self.price}"
def sort_products_by_price(products):
sorted_products = sorted(products, key=lambda x: x.price)
return sorted_products
# 创建一些产品对象
products = [
Product("Apple", 2.5),
Product("Banana", 1.2),
Product("Orange", 3.1),
Product("Grapes", 2.8)
]
# 按价格从低到高排序产品
sorted_products = sort_products_by_price(products)
# 打印排序后的产品
for product in sorted_products:
print(product)
输出结果将是:
Banana: 1.2
Apple: 2.5
Grapes: 2.8
Orange: 3.1
以上代码定义了一个Product
类来表示产品,其中包含名称和价格属性。sort_products_by_price
函数使用sorted
函数和一个lambda表达式作为键函数来对产品数组进行排序。最后,我们使用一个循环打印排序后的产品列表。