【问题标题】:Get the index from the comparison of two different length arrays从两个不同长度数组的比较中获取索引
【发布时间】:2019-02-28 20:39:59
【问题描述】:
#!usr/bin/perl -W

use strict;

my @a = (3,5,8,6,7,9);
my @b = (3,7,8);
my @index;
my $match;

foreach my $i (0 .. $#a) {
    $match = 0;
    foreach my $j (0 .. $#b) {
        if ($a[$i] == $b[$i]) {
            $match = 1;
            push (@index, $j);
            last;
        }            
    }
    if ($match == 1) {
        print "the values which got matched are $a[$i] at a and index is $i\n";
    }
}

print "the index of b matched is @index";

您好,我想获取数组元素匹配的索引和值。

my @a=(3,5,8,6,7,9); 
my @b=(5,9,3);

我想比较@a 和@b 并从a 中获取匹配值的索引。 (比较值,ia) 输出是这样的([5,9,3],[1,5,0])。 b 值 5 与索引 1 中的 a 匹配。

有人可以帮我解决这个问题吗?我试图首先获取匹配的数组元素并在找到匹配时推送索引。但是没有得到预期的结果。

【问题讨论】:

  • SO 不是免费的代码编写服务。您能否编辑问题以显示您已经尝试过的内容。
  • 如果我添加 != 并在 match =0 时提取元素,我得到 b 中不存在的元素的输出。但我想要匹配的元素及其索引。
  • 您的代码甚至无法编译
  • 我改进了代码的缩进。不客气,但请以后自己做。正确缩进的代码更易于阅读和理解。
  • if ($match = 1) - 你是这个意思吗?我怀疑你实际上想要if ($match == 1) 甚至只是if ($match)

标签: perl comparison matching


【解决方案1】:

为什么您的代码不起作用

您的代码中有一个相当简单的错字。

#                 V
if ($a[$i] == $b[$i]) {
    $match = 1;

    #              V
    push (@index, $j);
    last;
}

您每次都使用@a 中当前元素的$i 索引来访问@b 中的相同值,然后推送您从未用于比较的$j。您需要将$a[$i]$b[$j] 进行比较。一个字母的更改将使程序正常运行。

if ($a[$i] == $b[$j]) {
    $match = 1;
    push (@index, $j);
    last;
}

更好的方法

您的实施效率非常低。您要做的是从@b 查找@a 的内容。一种简单的方法是构建查找哈希(或 index,就像电话簿侧面的字母)。

use strict;
use warnings;
use 5.012; # for say and each on array

my @a = ( 3, 5, 8, 6, 7, 9 );
my @b = ( 5, 9, 3 );
my @index;
my $match;

my %index_of_a;
while ( my ( $index, $value ) = each @a ) {
  $index_of_a{$value} = $index;    # will overwrite
}

foreach my $value (@b) {
  if ( exists $index_of_a{$value} ) {
    say "The index of '$value' in \@a is '$index_of_a{$value}'";
  }
}

代码迭代@a 的值。它使用在 Perl 5.12 中添加的array form of each1。然后它将它们按值放入哈希中,这样您就可以在知道值时查找索引。

然后我们迭代@b 中的值并检查当前值的哈希中是否有@a 的索引。

输出如下所示

The index of '5' in @a is '1'
The index of '9' in @a is '5'
The index of '3' in @a is '0'

如果一个值在@a 中存在多次,将使用最后一次出现的值。我的代码没有跟踪 @b 的哪个索引何时匹配。我会把它留给你。


1) 虽然我通常不喜欢使用 each,但对于需要值和索引的数组,我发现它比 C 风格的 for 循环更具可读性。

【讨论】:

  • 您好,谢谢您的回答。我还有一个查询 @a=(3,5,8,6,7,9,9,8);那么我可以在匹配时获得多个索引值吗?即,@a 中 '9' 的索引是 5 ,6 ?
  • @Komala 您必须使用数组引用作为查找哈希的值并将索引推入其中。如果你不知道这意味着什么,我建议你看看perldoc.perl.org/perlreftut.html
  • 换句话说,将$index_of_a{$value} = $index;替换为push @{ $indexes_of_a{$value} }, $index;
猜你喜欢
  • 2013-04-02
  • 1970-01-01
  • 2021-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多