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

如何实现两个长度动态的数组元素全交叉组合配对?

数组元素两两组合解法

核心逻辑是通过双重遍历实现:外层遍历第一个数组的每个元素,内层遍历第二个数组的所有元素,将两者按元素1-元素2的格式拼接后收集到结果数组中。以下是几种主流编程语言的实现示例:

Python 实现

用列表推导式可以快速完成,代码简洁高效:

arr1 = ['a', 'b', 'c']
arr2 = ['1', '2']
result = [f"{x}-{y}" for x in arr1 for y in arr2]
print(result)  # 输出: ['a-1', 'a-2', 'b-1', 'b-2', 'c-1', 'c-2']

JavaScript 实现

推荐使用flatMap结合map的写法,避免手动维护结果数组:

const arr1 = ['a', 'b', 'c'];
const arr2 = ['1', '2'];
const result = arr1.flatMap(x => arr2.map(y => `${x}-${y}`));
console.log(result);  // 输出: ['a-1', 'a-2', 'b-1', 'b-2', 'c-1', 'c-2']

如果需要更直观的写法,也可以用嵌套forEach:

const result = [];
arr1.forEach(x => {
  arr2.forEach(y => {
    result.push(`${x}-${y}`);
  });
});
console.log(result);

Java 实现

通过嵌套增强for循环完成组合:

import java.util.ArrayList;
import java.util.List;

public class ArrayCombiner {
    public static void main(String[] args) {
        List<String> arr1 = List.of("a", "b", "c");
        List<String> arr2 = List.of("1", "2");
        List<String> result = new ArrayList<>();
        
        for (String elem1 : arr1) {
            for (String elem2 : arr2) {
                result.add(elem1 + "-" + elem2);
            }
        }
        
        System.out.println(result);  // 输出: [a-1, a-2, b-1, b-2, c-1, c-2]
    }
}

不管使用哪种语言,核心都是遍历第一个数组的每个元素,再与第二个数组的所有元素逐一拼接,这种逻辑可以适配任意长度的输入数组,完全满足动态元素数量的需求。

内容的提问来源于stack exchange,提问作者Elham Bagheri

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 20:52:15