如何用Pythonic方式合并数组相邻元素对生成新数组?
更Pythonic的相邻元素配对处理方案
给定数组:
arr = [{"location": 10, "value": 50}, {"location": 21, "value": 70}, {"location": 33, "value": 20}, {"location": 48, "value": 0}]
处理相邻元素对的函数:
def combine(current, next_item): # 注意:原参数名next是Python内置关键字,建议改为next_item避免冲突 return (next_item["location"] - current["location"]) * current["value"]
实现方式
利用zip()函数直接生成相邻元素对,搭配列表推导式或者map()函数即可完成,代码简洁且符合Python风格:
方式1:列表推导式(可读性更强)
result = [combine(current, next_item) for current, next_item in zip(arr, arr[1:])] print(result) # 输出: [550, 840, 300]
方式2:map函数(更简洁)
result = list(map(combine, arr, arr[1:])) print(result) # 输出: [550, 840, 300]
原理说明
zip(arr, arr[1:])会将原数组的第i个元素和第i+1个元素一一配对,生成恰好3组相邻元素对,完美匹配需求。后续只需对每一组元素应用combine函数即可得到目标结果。
内容的提问来源于stack exchange,提问作者Greg
相关产品推荐
相关产品推荐

