在Python中,可以使用sorted()
函数来对数组进行排序,并通过参数key
传入一个自定义的排序函数来按照不同的属性进行排序。下面是一个示例代码:
# 定义一个学生类
class Student:
def __init__(self, name, age, score):
self.name = name
self.age = age
self.score = score
def __repr__(self):
return f"Student(name={self.name}, age={self.age}, score={self.score})"
# 创建学生对象列表
students = [
Student("Alice", 18, 90),
Student("Bob", 19, 85),
Student("Charlie", 17, 95),
Student("David", 20, 80)
]
# 按照年龄升序排序
sorted_by_age = sorted(students, key=lambda student: student.age)
print(sorted_by_age)
# 按照分数降序排序
sorted_by_score = sorted(students, key=lambda student: student.score, reverse=True)
print(sorted_by_score)
输出结果为:
[Student(name=Charlie, age=17, score=95), Student(name=Alice, age=18, score=90), Student(name=Bob, age=19, score=85), Student(name=David, age=20, score=80)]
[Student(name=Charlie, age=17, score=95), Student(name=Alice, age=18, score=90), Student(name=Bob, age=19, score=85), Student(name=David, age=20, score=80)]
这样,我们就可以根据不同的属性对数组进行排序了。如果要分组,可以使用itertools.groupby()
函数来实现。