【发布时间】:2013-06-05 19:34:48
【问题描述】:
我正在尝试在 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总是返回字符串,从不引用。 -
@amon 谢谢,我对这一点感到困惑。