以下是一个示例代码,演示了如何使用关系属性进行过滤:
# 假设我们有一个包含人员信息的列表
people = [
{'name': 'John', 'age': 28, 'gender': 'male'},
{'name': 'Alice', 'age': 24, 'gender': 'female'},
{'name': 'Mike', 'age': 32, 'gender': 'male'},
{'name': 'Emily', 'age': 26, 'gender': 'female'}
]
# 定义一个函数,用于过滤人员列表
def filter_people(people_list, attribute, value):
filtered_people = []
for person in people_list:
if person.get(attribute) == value:
filtered_people.append(person)
return filtered_people
# 过滤出所有男性
males = filter_people(people, 'gender', 'male')
print(males)
# 过滤出年龄大于等于30岁的人
elderly = filter_people(people, 'age', 30)
print(elderly)
这个示例代码中,我们首先定义了一个包含人员信息的列表。然后,我们定义了一个filter_people()
函数,它接受一个人员列表、一个属性和一个值作为参数。该函数会遍历人员列表,对于每个人员,它会检查指定属性的值是否等于给定的值,如果是,则将该人员添加到一个新的列表中。最后,函数返回过滤后的人员列表。
在示例代码的最后,我们分别使用filter_people()
函数来过滤出所有男性和年龄大于等于30岁的人,并将结果打印出来。