基于两个条件提取并处理字典元素的Python函数实现需求
实现snatch函数的解决方案
下面是满足需求的snatch函数实现,附带测试示例和说明:
函数代码
def snatch(data, threshold): filtered = [] # 仅处理threshold中存在的key,自动排除无阈值的字段 for key in threshold: if key not in data: continue # 筛选当前字段中>=阈值的元素 filtered.extend(num for num in data[key] if num >= threshold[key]) # 计算均值,处理空列表避免除以0 return sum(filtered) / len(filtered) if filtered else 0.0
测试用例
1. 基础测试场景
data = { 'x': [1, 2, 3, 7], 'y': [1, 3, 7, 2] } threshold = { 'x': 3, 'y': 2 } print(snatch(data, threshold)) # 输出 4.4,对应(3+7+3+7+2)/5
2. 仅包含部分阈值的场景
data = { 'x': [1, 2, 3, 7], 'y': [1, 3, 7, 2] } threshold = { 'x': 3 } print(snatch(data, threshold)) # 输出 5.0,对应(3+7)/2
3. 无符合条件元素的场景
data = { 'x': [1,2], 'y': [0,1] } threshold = { 'x':3, 'y':2 } print(snatch(data, threshold)) # 输出 0.0
关键逻辑说明
- 遍历
threshold的key,确保只处理有阈值要求的字段,符合需求中“排除无阈值key对应元素”的规则 - 用生成器表达式筛选元素,相比列表推导式更节省内存(数据量大时更明显)
- 加入空列表判断,避免出现
ZeroDivisionError,返回0.0作为默认值(可根据实际需求调整)
内容的提问来源于stack exchange,提问作者Kash
相关产品推荐
相关产品推荐

