当前位置: 首页 > 知识库问答 >
问题:

如何从多个列表中得到笛卡尔积?

皇甫夕
2023-03-14

假设我有几个列表 ,我会将它们放入另一个列表或其他集合中,所以在调用列表 >.size() 之前,我不知道我有多少个列表

list1=[1,2]
list2=[3,4]
list3=[5,6]
....
listn=[2*n-1,2n];
list1*list2*list3

应该是:

[1,3,5],[1,3,6],[1,4,5],[1,4,6],[2,3,5],[2,3,6],[2,4,5],[2,4,6]

共有1个答案

蓝昊天
2023-03-14

您可以使用递归来实现它,递归的基本情况是当输入为空时返回空列表,否则处理剩余的元素。例如。

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

public class CartesianProduct {
    public static <T> List<List<T>> calculate(List<List<T>> input) {
        List<List<T>> res = new ArrayList<>();
        if (input.isEmpty()) { // if no more elements to process
            res.add(new ArrayList<>()); // then add empty list and return
            return res;
        } else {
            // we need to calculate the cartesian product
            // of input and store it in res variable
            process(input, res);
        }
        return res; // method completes , return result
    }

    private static <T> void process(List<List<T>> lists, List<List<T>> res) {
        //take first element of the list
        List<T> head = lists.get(0);
        //invoke calculate on remaining element, here is recursion
        List<List<T>> tail = calculate(lists.subList(1, lists.size()));

        for (T h : head) { // for each head
            for (List<T> t : tail) { //iterate over the tail
                List<T> tmp = new ArrayList<>(t.size());
                tmp.add(h); // add the head
                tmp.addAll(t); // and current tail element
                res.add(tmp);
            }
        }
    }

    public static void main(String[] args) {
        //we invoke the calculate method
        System.out.println(calculate(Arrays.asList(
                Arrays.asList(1, 2),
                Arrays.asList(3, 4),
                Arrays.asList(5, 6))));
    }
}

输出

[[1,3,5],[1,3,6],[1,4,5],[1,4,6],[2,3,5],[2,3,6],[2,4,5],[2,4,6]]
 类似资料:
  • 问题内容: 以下代码适用于,它是否也返回重复的笛卡尔积,如果是,如何获得唯一的笛卡尔积? 当我传递包含列表的列表时,这似乎也不起作用 问题答案: 要仅获取唯一元素,可以使用这样的set表示法( 注意: 这不能保证顺序) 或根据Paul Draper的评论,我们可以像这样 如果您也想维护订单 要使您的程序可以使用列表列表,只需将函数声明从 至

  • 问题内容: 我正在尝试编写一些代码来测试一堆输入参数的笛卡尔积。 我看过了,但是它的功能并不是我想要的。有没有一种简单明了的方法来获取一个字典,每个字典中包含任意数量的键 和 每个值中任意数量的元素,然后生成具有下一个排列的字典? 输入: 输出示例: 问题答案: 好的,感谢@dfan告诉我我在错误的位置查看。我现在知道了: 编辑 :经过多年的Python经验,我认为一个更好的解决方案是接受输入,而

  • 问题内容: 您将如何在JavaScript中实现多个数组的笛卡尔积? 举个例子, 应该回来 问题答案: 这是使用和提供的解决问题的功能解决方案(没有任何 可变变量 !),该提供者为:

  • 问题内容: 我想找到元素集的笛卡尔积。这是一个例子 笛卡尔积是, abc aba acc aca bbc bba bcc bca 笛卡尔积是, zbc ybc xbc 因此,我正在考虑一种在Java中执行的算法,该算法可以在一开始就找到在编译时定义的特定数量组的笛卡尔积。 问题答案: 您可以使用该方法从谷歌的番石榴库生成笛卡尔产品: 如果一切都那么简单!

  • 问题内容: 我试图解决中提到的问题这篇文章。考虑一个非负整数列表。我想要一套的笛卡尔积。例如,如果我可以使用itertools: 如果您能帮助我知道如何生成任意长度的using ,我将不胜感激。 问题答案: 您可以使用映射的所有项目来,然后解开他们:

  • 问题内容: 如何从一组列表中获得笛卡尔积(值的所有可能组合)? 输入: 所需的输出: 问题答案: 在Python 2.6+中