以下示例演示了如何使用Python对列表中的对象进行搜索并按条件过滤它们:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
people = [
Person("Alice", 25),
Person("Bob", 30),
Person("Charlie", 35),
Person("Dave", 40)
]
def filter_people(people_list, search_query):
filtered_people = []
for person in people_list:
if search_query.lower() in person.name.lower():
filtered_people.append(person)
return filtered_people
query = "a"
filtered_people = filter_people(people, query)
for person in filtered_people:
print(person.name)
在上面的示例中,“Person”类有两个属性 - “name”和“age”。我们有一个“people”列表,其中包含四个“Person”对象。我们编写了一个名为“filter_people”的函数,该函数接受要搜索的人员列表和查询以过滤人员的查询。该函数将查询字符串转换为小写,然后使用“in”运算符搜索人员的名称属性。如果查询条件匹配人员的名称,则将该人员添加到筛选人员列表中。最后,函数返回筛选过的人员列表。在我们的示例中,我们将查询设置为“a”,这将返回以“a”开头的所有人员的列表。我们可以迭代筛选后的人员列表并打印他们的名称。