在Python中,可以使用sorted()
函数来对对象数组进行排序。sorted()
函数可以接受一个可迭代对象作为参数,并返回一个新的已排序的列表。可以使用key
参数来指定排序的依据。
以下是一个示例代码,展示如何按特定顺序对对象数组进行排序:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f"Person(name={self.name}, age={self.age})"
# 创建对象数组
people = [
Person("Alice", 25),
Person("Bob", 30),
Person("Charlie", 20),
Person("David", 35)
]
# 定义排序顺序的函数
def sort_key(person):
order = {
"Alice": 1,
"Bob": 2,
"Charlie": 3,
"David": 4
}
return order.get(person.name, 5) # 默认排序值为5
# 按特定顺序对对象数组进行排序
sorted_people = sorted(people, key=sort_key)
# 打印排序结果
for person in sorted_people:
print(person)
输出结果为:
Person(name=Alice, age=25)
Person(name=Bob, age=30)
Person(name=Charlie, age=20)
Person(name=David, age=35)
在上述示例中,首先定义了一个Person
类,表示一个人对象,包含name
和age
属性。然后创建了一个对象数组people
,其中包含了4个Person
对象。
接下来,定义了一个sort_key
函数作为排序的依据。该函数根据name
属性返回一个对应的排序值。在这个示例中,我们按照Alice
、Bob
、Charlie
和David
的顺序对对象数组进行排序,其他的对象保持默认的排序值5。
最后,使用sorted()
函数对people
数组进行排序,并将排序结果赋值给sorted_people
。最后,遍历sorted_people
并打印排序结果。
通过定义一个返回特定排序值的函数作为sorted()
函数的key
参数,可以按特定顺序对对象数组进行排序。
下一篇:按特定顺序对多维数组进行排序