Perl的 - 内置功能"拉链"一起两列? [英] Perl - built-in function to "zipper" together two arrays?

查看:112
本文介绍了Perl的 - 内置功能"拉链"一起两列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

欲由数组A,从数组B中的第一个元素采取的第一个元素为相同长度的两个阵列合并成一个单一的阵列;从第二个因素后,由乙方第二个元素,等下面的程序说明算法:

I want to merge two arrays of equal length into a single array by taking the first element from array A, the first element from array B; second element from A, second element from B, etc. The following program illustrates the algorithm:

# 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内置函数,会做拉链相当于()。这将是在程序的最里面的循环中,并且需要尽可能快地运行。如果有一个内置的或CPAN模块不是,任何人都可以在我实施改进?

I'm wondering if I've overlooked a builtin function in Perl that will do the equivalent of zipper(). It will be at the innermost loop of the program, and needs to run as fast as possible. If there's not a built-in or a CPAN module, can anyone improve upon my implementation?

推荐答案

另一些人给出了问题的目/拉链一侧很好的答案,但如果你是刚刚从键阵列创建一个哈希和值中的一个就可以与下-AP $ p $做pciated 散片

Others have given good answers for mesh/zip side of the question, but if you are just creating a hash from an array of keys and one of values you can do it with the under-appreciated 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;

附录

我开始思考,为什么人们可以选择比其他的方法。我个人认为,该片实现是拉链的可读性,但其他人可能不同意。如果你经常这样做,你可能关心速度,在这种情况下,片形式是更快的。

I got to thinking why one may choose one method over the other. I personally think that the slice implementation is as readable as the zip, but others may disagree. If you are doing this often, you may care about speed, in which case the slice form is faster.

#!/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%    --

这篇关于Perl的 - 内置功能&QUOT;拉链&QUOT;一起两列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆