【问题标题】:How to do a cartesian product of a variable number of lists in Julia?如何在 Julia 中对可变数量的列表进行笛卡尔积?
【发布时间】:2021-11-15 12:30:08
【问题描述】:

对于集合 {1, 2, ..., n} 中的每个值 j,其中 n 的值可以变化(它是我的程序中的一些变量,根据用户的输入可能会有所不同),我有一个数组 A_j。我想获得所有数组 A_j 的笛卡尔积,这样我就可以遍历该笛卡尔积(从每个 A_1、A_2、... A_n 中取一个元素以获得一个元组(a_1、a_2、... , a_n) 在 A_1 x A_2 x ... x A_n) 中。我将如何在 Julia 中实现这一点?

【问题讨论】:

    标签: arrays julia cartesian-product


    【解决方案1】:

    使用Iterators.product:

    help?> Iterators.product
      product(iters...)
    
      Return an iterator over the product of several iterators. Each generated
      element is a tuple whose ith element comes from the ith argument iterator.
      The first iterator changes the fastest.
    
      Examples
      ≡≡≡≡≡≡≡≡≡≡
    
      julia> collect(Iterators.product(1:2, 3:5))
      2×3 Matrix{Tuple{Int64, Int64}}:
       (1, 3)  (1, 4)  (1, 5)
       (2, 3)  (2, 4)  (2, 5)
    

    【讨论】:

    • 是的,但是我忘了提(现在编辑了),n的值是不固定的。因此,就像在您的示例中一样,我们有一个固定值 n = 2。如果 n 可以变化,我们将如何完成它? n 只是我程序中的一些变量
    • 您可以通过splat 将向量导入产品Iterators.product(As...)
    • 我仍然不清楚如何做到这一点。您能否澄清一下我将如何使用 splat?
    • 你会像 @graphtheory12345678 一样使用它:Iterators.product(As...)。如果这不与您的代码结合使用,@VincentYu,您将必须提供一个最小的工作示例,以便发布者可以了解如何向您展示。当我们不知道变量的名称和类型时,不可能给您确切的代码。
    猜你喜欢
    • 2015-06-03
    • 2021-12-05
    • 2016-07-10
    • 1970-01-01
    • 2018-09-28
    • 2012-03-24
    • 2019-09-30
    • 1970-01-01
    • 2012-08-27
    相关资源
    最近更新 更多