Python中的itertools.product()等效于Perl

时间:2015-03-23 16:20:46

标签: python perl itertools

在Python中我可以使用itertools.product(),文档中说的是"笛卡尔积,相当于嵌套的for循环"。

在Perl中它的等价物是什么?

Python中的一个例子:

import itertools
opts_list = [["A","B"], ["C","D","E"], ["F","G"]]
print list(itertools.product(*opts_list))

给出:

  

[(' A',' C',' F'),(' A',' C' ;' G'),(' A',' D'' F'),' A' ,' D' G'),(' A',' E'' F'),( ' A',' E'' G'),(' B',' C',' ; F'),(' B',' C',' G'),(' B',' D',' F'),(' B',' D',' G'),(' B& #39;,' E',' F'),(' B',' E',' G' )]

4 个答案:

答案 0 :(得分:3)

我最终使用了:

use Math::Cartesian::Product;
cartesian {print "@_\n"} ["A","B"], ["C", "D", "E"], ["F", "G"];

答案 1 :(得分:2)

我使用Algorithm::Loops' NestedLoops

use Algorithm::Loops qw( NestedLoops );

my $iter = NestedLoops([["A","B"], ["C","D","E"], ["F","G"]]);
while (my @items = $iter->()) {
    ...
}

答案 2 :(得分:1)

我喜欢Set::CrossProduct

#!/usr/bin/env perl

use strict;
use warnings;

use Set::CrossProduct;

my $it = Set::CrossProduct->new([
     ["A","B"],
     ["C","D","E"],
     ["F","G"]
]);

while (my $v = $it->get) {
    print "@$v\n";
}

答案 3 :(得分:0)

您应该使用其他答案中引用的其中一个CPAN模块。但作为一个有趣的练习,我编写了自己的函数来返回任意数量的输入数组引用的笛卡尔积。

my $combinations = get_combinations(["A","B"], ["C","D","E"], ["F","G"]);

foreach my $combo (@$combinations) {
  print "@$combo\n";
}

sub get_combinations {
  my @arrays = @_;

  # pre-determine to the total number of combinations
  my $total = 1;
  foreach my $aref (@arrays) {
    # if our array is empty, add 1 undef item
    push(@$aref, undef) unless scalar @$aref;
    $total *= scalar @$aref;
  }

  my $matrix = [];
  my $block_size = $total;
  for (my $col = 0; $col <= $#arrays; $col++) {
    # determine the number of consecutive times to print each item in the column
    $block_size = $block_size / scalar @{$arrays[$col]};

    # fill-in our 2-D array (matrix), one column (input array) at a time
    for (my $row = 0; $row < $total; $row++) {
      my $item_index = int($row / $block_size) % scalar @{$arrays[$col]};
      $matrix->[$row]->[$col] = $arrays[$col]->[$item_index];
    }

  }

  return wantarray ? @$matrix : $matrix;
}