我想通过从数组A中获取第一个元素,从数组B中获取第一个元素,将两个长度相等的数组合并为一个数组; A 中的第二个元素,B 中的第二个元素等。以下程序说明了该算法:
# file zipper.pl
use strict;
use warnings;
use 5.010;
my @keys = qw/abel baker charlie dog easy fox/;
my @values = qw/a b c d e f/;
# ==> Is there a builtin function that is equivalent of zipper()? <==
#
my %hash = zipper( \@keys, \@values );
while ( my ( $k, $v ) = each %hash ) {
say "$k=$v";
}
# zipper(): Take two equal-length arrays and merge them (one from A, one from B,
# another from A, another from B, etc.) into a single array.
#
sub zipper {
my $k_ref = shift;
my $v_ref = shift;
die "Arrays must be equal length" if @$k_ref != @$v_ref;
my $i = 0;
return map { $k_ref->[ $i++ ], $_ } @$v_ref;
}
输出
$ ./zipper.pl
easy=e
dog=d
fox=f
charlie=c
baker=b
abel=a
我想知道我是否忽略了 Perl 中一个相当于 zipper() 的内置函数。它将位于程序的最内层循环,并且需要尽可能快地运行。如果没有内置或 CPAN 模块,任何人都可以改进我的实现吗?
最佳答案
其他人已经为问题的网格/zip 方面给出了很好的答案,但是如果您只是从一组键和一个值创建散列,您可以使用未被重视的 hash slice 来完成。 .
#!/usr/bin/env perl
use strict;
use warnings;
my @keys = qw/abel baker charlie dog easy fox/;
my @values = qw/a b c d e f/;
my %hash;
@hash{@keys} = @values;
use Data::Dumper;
print Dumper \%hash;
附录
我开始思考为什么一个人可能会选择一种方法而不是另一种。我个人认为 slice 实现和 zip 一样具有可读性,但其他人可能不同意。如果您经常这样做,您可能会关心速度,在这种情况下,切片形式会更快。
#!/usr/bin/env perl
use strict;
use warnings;
use List::MoreUtils qw/zip/;
use Benchmark qw/cmpthese/;
my @keys = qw/abel baker charlie dog easy fox/;
my @values = qw/a b c d e f/;
cmpthese( 100000, {
zip => sub {
my %hash = zip @keys, @values;
},
slice => sub {
my %hash;
@hash{@keys} = @values;
},
});
结果:
Rate zip slice
zip 51282/s -- -34%
slice 78125/s 52% --
关于arrays - Perl - 将 "zipper"两个数组放在一起的内置函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16755642/