以下是一种按照未知属性名称进行筛选的解决方法的示例代码:
# 假设我们有一个包含多个字典的列表
data = [
{"name": "John", "age": 25, "city": "New York"},
{"name": "Alice", "age": 30, "city": "London"},
{"name": "Bob", "age": 35, "city": "Paris"}
]
# 定义一个函数来筛选具有指定属性和值的字典
def filter_by_attribute(data, attribute, value):
filtered_data = []
for d in data:
if attribute in d and d[attribute] == value:
filtered_data.append(d)
return filtered_data
# 使用示例
filtered_data = filter_by_attribute(data, "age", 30)
print(filtered_data)
# 输出: [{'name': 'Alice', 'age': 30, 'city': 'London'}]
filtered_data = filter_by_attribute(data, "city", "Paris")
print(filtered_data)
# 输出: [{'name': 'Bob', 'age': 35, 'city': 'Paris'}]
在上述示例代码中,我们定义了一个名为filter_by_attribute
的函数,该函数接受一个列表data
、一个字符串attribute
和一个值value
作为参数。函数遍历列表中的字典,检查是否存在具有指定属性的字典,并且该属性的值等于给定的值。如果满足条件,则将该字典添加到结果列表中。最后,函数返回筛选后的结果列表。
可以根据具体的需求,修改函数代码中的属性名称和值,以实现按照不同的未知属性进行筛选。