Perl - “拉链"的内置函数两个数组一起? [英] Perl - built-in function to "zipper" together two arrays?

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

问题描述

我想通过从数组 A 中取出第一个元素,从数组 B 中取出第一个元素,将两个等长的数组合并为一个数组;来自 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 中的一个内置函数,它的作用相当于 zipper().它将位于程序的最内层循环,并且需要尽可能快地运行.如果没有内置或 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?

推荐答案

其他人已经对问题的网格/zip 方面给出了很好的答案,但是如果您只是从一组键和一个值中创建一个散列,您可以使用被低估的 hash slice 来实现.

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;

附录

我开始思考为什么人们可能会选择一种方法而不是另一种方法.我个人认为切片实现与 zip 一样可读,但其他人可能不同意.如果你经常这样做,你可能会关心速度,在这种情况下切片形式会更快.

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 - “拉链"的内置函数两个数组一起?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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