使用Perl中的列表

时间:2014-02-17 08:37:43

标签: perl

我有两个列表a和b如下:

a = ('church.n.01','church.n.02','church_service.n.01','church.n.04')  
b = ('temple.n.01','temple.n.02','temple.n.03','synagogue.n.01')

我想使用函数get_relatedness(arg1,arg2)找到a和b成员之间的相关性。我如何操作Perl中的a和b,以便在Perl中使用两个嵌套for循环传递a和b之间的所有可能组合。

请帮我解决这个问题,因为我是Perl的新手。

2 个答案:

答案 0 :(得分:1)

my @a = ('church.n.01','church.n.02','church_service.n.01','church.n.04');
my @b = ('temple.n.01','temple.n.02','temple.n.03','synagogue.n.01');

use Data::Dumper; 
print Dumper [ get_relatedness(\@a, \@b) ];

sub get_relatedness {
  my ($c, $d) = @_;

  return map { my $t=$_; map [$t, $_], @$d } @$c;
}

输出

$VAR1 = [
      [
        'church.n.01',
        'temple.n.01'
      ],
      [
        'church.n.01',
        'temple.n.02'
      ],
      [
        'church.n.01',
        'temple.n.03'
      ],
      [
        'church.n.01',
        'synagogue.n.01'
      ],
      [
        'church.n.02',
        'temple.n.01'
      ],
      [
        'church.n.02',
        'temple.n.02'
      ],
      [
        'church.n.02',
        'temple.n.03'
      ],
      [
        'church.n.02',
        'synagogue.n.01'
      ],
      [
        'church_service.n.01',
        'temple.n.01'
      ],
      [
        'church_service.n.01',
        'temple.n.02'
      ],
      [
        'church_service.n.01',
        'temple.n.03'
      ],
      [
        'church_service.n.01',
        'synagogue.n.01'
      ],
      [
        'church.n.04',
        'temple.n.01'
      ],
      [
        'church.n.04',
        'temple.n.02'
      ],
      [
        'church.n.04',
        'temple.n.03'
      ],
      [
        'church.n.04',
        'synagogue.n.01'
      ]
    ];

答案 1 :(得分:1)

要使用两个嵌套循环比较两个数组中元素的所有组合,您只需要遍历一个,并且对于第一个数组的每个元素,在第二个数组的元素上执行内部循环:

my @a = ('church.n.01','church.n.02','church_service.n.01','church.n.04');
my @b = ('temple.n.01','temple.n.02','temple.n.03','synagogue.n.01');

my $relatedness;

for my $outer (@a) {
  for my $inner (@b) {
    $relatedness += get_relatedness($outer, $inner);
  }
}