以下是一个按属性对三个不同的对象数组进行排序的示例代码:
class Object:
def __init__(self, name, age, height):
self.name = name
self.age = age
self.height = height
# 创建对象数组
objects1 = [Object("Tom", 25, 180), Object("Alice", 30, 165), Object("Bob", 20, 175)]
objects2 = [Object("John", 28, 170), Object("Linda", 35, 160), Object("David", 22, 185)]
objects3 = [Object("Sarah", 27, 175), Object("Michael", 32, 190), Object("Emma", 24, 160)]
# 按属性排序函数
def sort_objects(objects, key):
return sorted(objects, key=lambda obj: getattr(obj, key))
# 按属性对三个对象数组进行排序
sorted_objects1 = sort_objects(objects1, "name")
sorted_objects2 = sort_objects(objects2, "age")
sorted_objects3 = sort_objects(objects3, "height")
# 打印排序结果
print("Sorted objects1:")
for obj in sorted_objects1:
print(obj.name, obj.age, obj.height)
print("Sorted objects2:")
for obj in sorted_objects2:
print(obj.name, obj.age, obj.height)
print("Sorted objects3:")
for obj in sorted_objects3:
print(obj.name, obj.age, obj.height)
这段代码创建了一个Object
类,它包含了name
、age
和height
属性。然后,我们创建了三个不同的对象数组objects1
、objects2
和objects3
。接下来,定义了一个sort_objects
函数,它接受一个对象数组和一个属性名作为参数,使用getattr
函数获取对象的属性值,并通过lambda
表达式作为key
函数进行排序。最后,通过调用sort_objects
函数对三个对象数组进行排序,并打印排序结果。
下一篇:按属性对数组进行排序段