我正在尝试比较2个巨大的数组,并希望使用地图。我在这里使用唯一的密钥概念来匹配索引。
我的阵列:
my @array1 = ( ['a','b','c','d'], ['e','f','g','h'], ['i','j','k','l'], ['m','n','o','p'], ['q','r','s','t']);
my @array2 = ( ['r','q','s','t'], ['b','a','c','d'], ['n','m','o','p'], ['f','e','g','h'], ['j','i','k','l']);
我独特的钥匙:
my @uk1 = (0,2,3);
my @uk2 = (1,2,3);
这些数组规模庞大,每个指数超过30,000个,每个指数中包含20多个元素。
如此有效地我创建了一个地图
for ( my $j = 0; $j <= $#array1 ; $j++ )
{
my searchString;
for ( my $k = 0; $k <= $#uk1; $k++ )
{
if ( $k != 0 )
{
$searchString .= ","
}
$my searchString .= $array1[$j][$uk[$k];
}
my @result = map { $_ }
grep { join (",",$array2[$_][1],$array2[$_][2],$array2[$_][3]) ) =~ join(",",$array1[$j][0],$array1[$j][1],$array1[$j][2]) }
0 .. $#array;
}
返回匹配的索引。
我的问题是,我如何依赖于唯一键呢?因为唯一键的长度会不断变化,据我所知,我无法动态创建$ array2 [$ _]连接部分。
希望我的问题足够明确。
我希望有比较的逻辑
$array1[$uk1[0]],$array1[$uk1[1]],$array1[$uk1[2]] and so on (depending on the number of keys in UK) with
$array2[$uk2[0]],$array2[$uk2[1]],$array2[$uk2[2]].......
答案 0 :(得分:2)
也许,
my @array1 = ( ['a','b','c','d'], ['e','f','g','h'], ['i','j','k','l'], ['m','n','o','p'], ['q','r','s','t']);
my @array2 = ( ['r','q','s','t'], ['b','a','c','d'], ['n','m','o','p'], ['f','e','g','h'], ['j','i','k','l']);
my @result;
for my $i (0 .. $#array1) {
push @result,
map { [$i, $_] }
grep {
"@{ $array1[$i] }[1,2,3]" eq "@{ $array2[$_] }[0,2,3]"
}
0 .. $#array2;
}
use Data::Dumper; print Dumper \@result;
输出
$VAR1 = [
[
0,
1
],
[
1,
3
],
[
2,
4
],
[
3,
2
],
[
4,
0
]
];
答案 1 :(得分:1)
您想要使用的是数组切片:
但也让生活更轻松:
for my $sample ( @array1 )
{
my $test= join(",", @$sample[@uk1]) ;
my @result = grep { $_ eq $test } map { join(",", @$_[@uk2] ) } @array2 ;
say "huzzah" if @result ;
}
Perl允许您通过“数组切片”指定数组中的多个元素:
my @list= ('a', 'b', 'c', 'd') ;
my @pieces= @list[1,3] ;