如何实现两个array相同索引位置元素相加,适配动态长度的数组?
同索引位置元素逐位相加实现方案
以下是不同开发语言下的最优实现方式,均支持动态可变的数组长度:
Python 实现
优先使用内置的zip函数配对同索引元素,结合列表推导式完成操作,默认以最短数组长度为基准,底层为C实现逻辑,性能远高于手动遍历索引的写法:
a = ['a', 'b', 'c'] b = ['d', 'e', 'f'] result = [x + y for x, y in zip(a, b)] # 输出:['ad', 'be', 'cf']
如果需要按最长数组长度处理、缺失位补默认值,可以使用标准库的itertools.zip_longest:
from itertools import zip_longest a = ['a', 'b'] b = ['d', 'e', 'f'] result = [x + y for x, y in zip_longest(a, b, fillvalue='')] # 输出:['ad', 'be', 'cf']
JavaScript 实现
优先使用数组原生map方法遍历,直接取对应索引的元素操作,无需引入额外依赖:
const a = ['a', 'b', 'c']; const b = ['d', 'e', 'f']; const result = a.map((item, index) => item + b[index]); // 输出:['ad', 'be', 'cf']
适配长度不一致场景、按最长数组处理的写法:
const a = ['a', 'b']; const b = ['d', 'e', 'f']; const maxLen = Math.max(a.length, b.length); const result = Array.from({length: maxLen}, (_, i) => (a[i] ?? '') + (b[i] ?? '')); // 输出:['ad', 'be', 'cf']
通用实现原则
其他语言的实现可遵循两个核心原则保障最优性:
- 优先使用语言内置的迭代器/配对函数,避免手动维护索引变量,降低出错概率
- 优先调用原生编译实现的方法,性能远高于手写循环的解释执行效率
内容的提问来源于stack exchange,提问作者Yash
相关产品推荐
相关产品推荐

