In Perl, how do I make hash from arrays @A
and @B
having equal number of elements? The goal is to have each value of @A
as key to value in @B
. The resulting hash %C
would,then make it possible to uniquely identify an element from @B
supplying key from @A
.
在Perl中,如何从具有相同数量元素的数组@A和@B进行散列?目标是让@A的每个值成为@B中值的关键。得到的散列%C然后可以唯一地标识来自@A的@B提供密钥的元素。
4 个解决方案
#1
23
it's as simple as
它很简单
my %c;
@c{@a} = @b;
#2
8
use List::MoreUtils 'mesh';
my %c = mesh @a, @b;
That's how it's made internally (if you're sure about equal number of elements):
这就是内部制作的方式(如果您确定元素数量相等):
my %c = map { $a[$_] => $b[$_] } 0 .. $#a;
#3
2
If I understand the problem correctly:
如果我正确理解了问题:
my %c;
$c{$a[$_]} = $b[$_] for (0 .. @a-1);
#4
0
A's are the keys, B's are the values of hash C:
A是键,B是散列C的值:
use strict;
use warnings;
my @a = 1 .. 3;
my @b = 4 .. 6;
my %c;
for (0 .. $#a) {
$c{$a[$_]} = $b[$_]
}
Keep in mind that there must not be any duplicate values in the A array.
请记住,A数组中不得有任何重复值。
#1
23
it's as simple as
它很简单
my %c;
@c{@a} = @b;
#2
8
use List::MoreUtils 'mesh';
my %c = mesh @a, @b;
That's how it's made internally (if you're sure about equal number of elements):
这就是内部制作的方式(如果您确定元素数量相等):
my %c = map { $a[$_] => $b[$_] } 0 .. $#a;
#3
2
If I understand the problem correctly:
如果我正确理解了问题:
my %c;
$c{$a[$_]} = $b[$_] for (0 .. @a-1);
#4
0
A's are the keys, B's are the values of hash C:
A是键,B是散列C的值:
use strict;
use warnings;
my @a = 1 .. 3;
my @b = 4 .. 6;
my %c;
for (0 .. $#a) {
$c{$a[$_]} = $b[$_]
}
Keep in mind that there must not be any duplicate values in the A array.
请记住,A数组中不得有任何重复值。