以下是一个示例代码,演示了如何按照列表对象的字段属性筛选列表。
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# 创建一个包含 Person 对象的列表
people = [
Person("Alice", 25),
Person("Bob", 30),
Person("Charlie", 20),
Person("Dave", 35)
]
# 定义一个函数,用于根据年龄筛选人员
def filter_by_age(person):
return person.age > 25
# 使用 filter() 函数筛选符合条件的人员
filtered_people = list(filter(filter_by_age, people))
# 打印筛选结果
for person in filtered_people:
print(person.name, person.age)
在上述示例中,我们首先定义了一个 Person 类,该类有两个属性:name 和 age。然后,我们创建了一个包含 Person 对象的列表。
接下来,我们定义了一个 filter_by_age 函数,该函数接受一个 Person 对象,并根据年龄属性进行筛选。在主程序中,我们使用 filter() 函数和 filter_by_age 函数对人员列表进行筛选,将符合条件的人员存储在 filtered_people 列表中。
最后,我们遍历 filtered_people 列表,并打印每个人员的姓名和年龄。
你可以根据自己的需求修改 filter_by_age 函数来实现不同的筛选条件。
下一篇:按照列表分组并为每个值创建新列