You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 02:24:55