python中列表列表之间的交叉乘积

时间:2021-03-07 13:55:34

标签: python python-3.x list

假设我有 2 个列表,如下所示:

list1=[[1],[2],[3]]
list2=[[4],[5]]

我想做的是这两个列表中的列表项之间的交叉积。在这个例子中,结果是:

    result_list=[[1,4],[1,5],[2,4],[2,5],[3,4],[3,5]]

如何使用 python 完成此操作?我在网上搜索了一些,但我找不到解决方案,我一直被卡住了。非常欢迎任何帮助。

提前致谢!!

4 个答案:

答案 0 :(得分:6)

你可以试试itertools.product

from itertools import product
list1=[[1],[2],[3]]
list2=[[4],[5]]

output = [[x[0][0], x[1][0]] for x in product(list1, list2)]

print(output)
[[1, 4], [1, 5], [2, 4], [2, 5], [3, 4], [3, 5]]

答案 1 :(得分:2)

那是笛卡尔积,但由于您有 2 级列表作为输入,因此您需要一些技巧来获得结果

  • 在产品之后展平结果

    from itertools import product, chain
    res = [list(chain(*r)) for r in product(list1, list2)]
    
  • 在产品之前展平输入列表

    res = list(product(chain(*list1), chain(*list2)))
    

如果你有一级列表,那就是

list1 = [1, 2, 3]
list2 = [4, 5]
res = list(product(list1, list2))
print(res)  # [(1, 4), (1, 5), (2, 4), (2, 5), (3, 4), (3, 5)]

答案 2 :(得分:0)

scroll-margin-top: 2rem;

答案 3 :(得分:0)

从 itertools 中,product 将生成所需的配对,但输出将是项目列表的元组。您可以使用 chain.from_iterable 组合这些列表并将结果有效地映射到列表:

from itertools import product,chain
result_list = [*map(list,map(chain.from_iterable,product(list1,list2)))]

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