以下是一个示例代码,展示如何按照客户优先级对列表进行属性排序:
class Customer:
def __init__(self, name, priority):
self.name = name
self.priority = priority
def __repr__(self):
return f"Customer('{self.name}', {self.priority})"
customers = [
Customer('John', 2),
Customer('Alice', 1),
Customer('Bob', 3),
Customer('Charlie', 1),
]
# 按照客户优先级升序排序
sorted_customers = sorted(customers, key=lambda customer: customer.priority)
for customer in sorted_customers:
print(customer)
运行上述代码,输出结果如下:
Customer('Alice', 1)
Customer('Charlie', 1)
Customer('John', 2)
Customer('Bob', 3)
代码中创建了一个Customer
类,其中有name
和priority
两个属性。然后创建了一个包含多个Customer
对象的列表customers
。
使用sorted()
函数对customers
列表进行排序,通过key
参数指定排序的依据,这里使用lambda
函数指定按照customer.priority
进行排序。
最后,通过遍历排序后的列表输出排序结果。