要按指定顺序对对象属性进行排序,可以使用自定义的比较函数来实现。以下是一个示例代码:
class Person:
def __init__(self, name, age, city):
self.name = name
self.age = age
self.city = city
people = [
Person("Alice", 25, "New York"),
Person("Bob", 30, "London"),
Person("Charlie", 20, "Paris")
]
# 指定属性的排序顺序
order = ["name", "age", "city"]
# 自定义比较函数
def custom_compare(obj):
return [getattr(obj, attr) for attr in order]
# 使用自定义比较函数进行排序
sorted_people = sorted(people, key=custom_compare)
# 输出排序结果
for person in sorted_people:
print(person.name, person.age, person.city)
在上面的示例中,我们首先定义了一个 Person
类来表示人员对象,包含 name
、age
和 city
属性。然后创建了一个包含多个 Person
对象的列表 people
。
接下来,我们定义了一个 order
列表,用于指定属性的排序顺序。在这个例子中,我们按照 name
、age
和 city
的顺序进行排序。
然后,我们定义了一个自定义比较函数 custom_compare
,该函数接受一个对象作为参数,并返回一个包含属性值的列表,该列表按照 order
列表中指定的顺序进行排序。
最后,我们使用 sorted
函数对 people
列表进行排序,通过指定 key
参数为自定义比较函数 custom_compare
来实现按指定顺序排序。
最终,我们按照排序结果输出了每个人员对象的属性值。根据上面的示例代码,最终输出的结果将按照指定的顺序对对象属性进行排序。
下一篇:按指定顺序对R数据框进行排序