我想在Perl中编写一个计算两个字符串的交叉乘积(笛卡尔乘积)的函数。我在Python中有类似的代码,看起来像这样:两个字符串的笛卡尔积
def cross(A, B):
"Cross product of elements in A and elements in B."
return [a+b for a in A for b in B]
我怎样才能以优雅的方式模仿这个列表理解?
这是我到目前为止有:
# compute the cross product of two Strings
# cross('12','AB') = ((1,A), (1,B), (2,A), (2,B))
sub cross {
# unpack strings
my ($A, $B) = @_;
# array to hold products
my @out_array;
# split strings into arrays
my @A_array = split(//, $A);
my @B_array = split(//, $B);
# glue the characters together and append to output array
for my $r (@A_array) {
for my $c (@B_array) {
push @out_array, [$r . $c];
}
}
return \@out_array;
}
这不是工作正是我所期望的,由于某种原因,参考即将由split()
,而不是一个列表返回。
任何建议或其他更多优雅的笛卡尔产品解决方案将不胜感激。
'push @out_array,[$ r。 $ c];'将包含一个字符串的数组引用推送到'@ out_array'。你不需要参考,所以跳过方括号。 'split' * always *返回字符串,永远不会引用。 – amon
@amon谢谢,我对这一点感到困惑。 –