在Numpy中如何实现两个字符串数组的对应元素类乘法拼接?
实现方案
你需要的是两个等长列表的对应位置元素配对拼接,不同常用语言的实现如下:
- Python 实现
最简洁的方式是结合zip()和列表推导:
要是需要处理不等长的列表,按最长长度拼接可以用x = ['a', 'b'] y = ['c', 'd'] z = [f"{a} x {b}" for a, b in zip(x, y)]itertools.zip_longest:from itertools import zip_longest # fillvalue 可以自定义缺省位置的填充值 z = [f"{a} x {b}" for a, b in zip_longest(x, y, fillvalue='')] - JavaScript 实现
用map按索引取对应元素拼接即可:const x = ['a', 'b'] const y = ['c', 'd'] const z = x.map((item, idx) => `${item} x ${y[idx]}`)
内容的提问来源于stack exchange,提问作者Gourav
相关产品推荐
相关产品推荐

