写一个根据n个条件对list进行过滤的共通方法
时间: 2024-05-13 11:20:57 浏览: 81
以下是一个根据n个条件对list进行过滤的Python方法:
```python
def filter_list(lst, conditions):
"""
根据条件对list进行过滤
:param lst: 需要过滤的list
:param conditions: 过滤条件,为一个字典,键为属性名,值为属性值
:return: 过滤后的list
"""
filtered_lst = lst
for key, value in conditions.items():
filtered_lst = [item for item in filtered_lst if item.get(key) == value]
return filtered_lst
```
使用方法:
```python
lst = [
{"name": "张三", "age": 20, "gender": "男"},
{"name": "李四", "age": 25, "gender": "男"},
{"name": "王五", "age": 30, "gender": "女"},
{"name": "赵六", "age": 35, "gender": "女"},
]
conditions = {"age": 25, "gender": "男"}
filtered_lst = filter_list(lst, conditions)
print(filtered_lst)
```
输出结果:
```python
[{'name': '李四', 'age': 25, 'gender': '男'}]
```
以上方法基于字典的键值对进行过滤,可以根据实际情况修改。
阅读全文