以下是一个示例代码,展示了如何按照属性删除排序:
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("John", 25),
Person("Alice", 30),
Person("Bob", 20)
]
sorted_people = sorted(people, key=lambda x: x.age) # 按照年龄排序
print(sorted_people)
# 删除年龄大于等于30的人
sorted_people = [person for person in sorted_people if person.age < 30]
print(sorted_people)
输出结果:
[Person(name='Bob', age=20), Person(name='John', age=25), Person(name='Alice', age=30)]
[Person(name='Bob', age=20), Person(name='John', age=25)]
在上述示例中,我们定义了一个Person
类,它具有name
和age
属性。然后,我们创建了一个包含几个Person
对象的列表people
。
接下来,我们使用sorted()
函数和key
参数来按照age
属性对people
进行排序,并将结果保存在sorted_people
列表中。在这里,我们使用了一个lambda函数作为key
参数来指定排序的依据,即按照x.age
进行排序。
最后,我们使用列表推导式来删除sorted_people
中年龄大于等于30的人,结果保存在sorted_people
列表中,并打印出最终结果。