从Perl中的2个数组获取相同的元素和索引

时间:2019-05-27 14:44:54

标签: arrays perl indexing comparison

我是Perl的新手,我正在尝试解决以下比较问题。

我有两个数组:
@A =(“红色”,“绿色”,“黄色”);
@B =(“黄色”,“黑色”,“黄色”,“红色”,“白色”,“黄色”);

在数组A中,每个元素仅出现一次。
在数组B中,每个元素可以出现零次,一次或多次。

对于A中的每个元素,代码应列出其在B中的位置,并给出如下输出:

>红色处为索引3。
>缺少绿色。
>在索引0、2和5处为黄色。
>在A中检测到4次来自B的元素。

我尝试了以下操作,但是在比较两个数组之后我无法弄清楚如何列出元素的索引

foreach $x (@A){
    foreach $y (@B){
    if ($y eq $x){
    print "$y\n";
    }
    elsif ($x ne$y){
    print "$x";
    }
  }
}

有人可以帮帮我吗?提前非常感谢您! 雷比

2 个答案:

答案 0 :(得分:0)

这里是一个例子:

my @A = ("Red", "Green", "Yellow");
my @B = ("Yellow", "Black","Yellow","Red", "White", "Yellow");
my %indices;
for my $i (0..$#B) {
    push @{ $indices{$B[$i]} }, $i;
}
my $count = 0;
for (@A) {
    if (exists $indices{$_} ) {
        my @temp = @{ $indices{$_} };
        $count += (scalar @temp);
        print "$_ is at index: ", @temp, "\n";
    }
    else {
        print "$_ is missing\n";
    }
}
print "Elements from B were detected ", $count, " times in A.\n";

答案 1 :(得分:0)

这是一种简单的方法。计数和切换变量可跟踪是否找到或缺少某项:

my @a = ("Red", "Green", "Yellow");
my @b = ("Yellow", "Black","Yellow","Red", "White", "Yellow");
my $count = 0;
for my $ael (0 .. $#a) {
 my $switch = "off";
 for my $bel (00 .. $#b) {
  if ($a[$ael] eq $b[$bel]) {
  $count++;
  $switch = "on"; 
print "$b[$bel] found at index $bel\n";
                            }
                         }
print "$a[$ael] is missing\n" if $switch eq "off";  
                        }
print "Elements from B found $count times in A";

输出:

Red found at index 3
Green is missing
Yellow found at index 0
Yellow found at index 2
Yellow found at index 5
Elements from B found 4 times in A