【问题标题】:How can I compute the cartesian product between two numpy arrays? [duplicate]如何计算两个 numpy 数组之间的笛卡尔积? [复制]
【发布时间】:2021-08-05 07:45:28
【问题描述】:

我有两个 numpy 数组:alpha=[0,1]beta=[2,3,4]。 我想将它们组合起来以创建一个新的元组数组,它​​是前两个数组的所有可能组合的结果。

x= [(0,2)(0,3)(0,4)(1,2)(1,3)(1,4)]

在 numpy 包中是否有一个功能,或者我需要自己做?如果我必须这样做,哪种方式是最佳方式?

【问题讨论】:

  • 订单算不算?

标签: python arrays numpy cartesian-product


【解决方案1】:

你可以使用itertools.product:

import numpy as np
import itertools


alpha = np.array([0, 1])
beta = np.array([2, 3, 4])

x = list(itertools.product(alpha, beta))

print(x)
# [(0, 2), (0, 3), (0, 4), (1, 2), (1, 3), (1, 4)]

【讨论】:

    【解决方案2】:
    alpha=[0,1]
    beta=[2,3,4]
    
    d = [(a, b) for a in alpha for b in beta] # The cartesian product
    
    print(d)
    

    【讨论】:

      猜你喜欢
      • 2020-12-10
      • 2017-03-05
      • 2021-02-17
      • 1970-01-01
      • 1970-01-01
      • 2016-02-24
      • 2011-05-27
      • 2020-05-08
      • 2016-04-21
      相关资源
      最近更新 更多