【问题标题】:How to get all the possible combinations of multiple lists? [duplicate]如何获得多个列表的所有可能组合? [复制]
【发布时间】:2021-05-10 11:10:36
【问题描述】:

我有多个这样的列表(可以是任何长度和数字):

['a1', 'a2']
['b1', 'b2', 'b3']

我不知道如何获得这些列表的所有可能组合, 想要的结果:

[
  ['a1', 'b1'],
  ['a1', 'b2'],
  ['a1', 'b3'],
  ['a2', 'b1'],
  ['a2', 'b2'],
  ['a2', 'b3']
]

有人对此有什么建议吗(任何语言都可以)?我尝试使用递归但没有运气。

【问题讨论】:

标签: javascript python c# arrays


【解决方案1】:

如果我理解正确(我不确定)但在 java 中你应该使用 Set 来消除重复,那么:

    List<String> list = Arrays.asList("a1", "a2");

    List<String> anotherList = Arrays.asList("b1", "b2", "b3");

    Set<String> set = new HashSet<>(list);
    Set<String> anotherSet = new HashSet<>(anotherList);

    set.stream()
        .forEach(setElement -> anotherSet.stream()
            .forEach(anotherSetElement -> System.out.println(setElement + " " + anotherSetElement)));

【讨论】:

  • 这适用于 2 个数组,但我可以有任意数量的数组
猜你喜欢
  • 1970-01-01
  • 2010-10-02
  • 1970-01-01
  • 2012-06-05
  • 1970-01-01
  • 2013-02-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多