可以使用Python中的内置函数sorted()来对列表中的对象按照指定属性进行排序。假设有一个Person类,其中有属性name和age,需要按照age属性对列表进行排序,则代码如下:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person('Alice', 25)
p2 = Person('Bob', 20)
p3 = Person('Charlie', 30)
people = [p1, p2, p3]
# 按年龄对人物列表进行排序,只保留年龄这个属性的值
result = sorted(people, key=lambda x: x.age)
# 打印排序后的结果
for p in result:
print(p.age)
运行结果为:
20
25
30
上一篇:按对象属性值从列表中选择对象?