计算一组数组中元素的出现次数

时间:2014-08-02 12:05:06

标签: perl

如何计算数组中特定值的出现次数?

我的Perl代码

@a  = qw(one two three four);
@b  = qw(one one two four four);
@c  = qw(four two one one);
@d  = qw(four);
@f  = qw(one two);

@ta = ("@a", "@b", "@c", "@d", "@f");
@ar = qw(one two three four);

foreach (@ta) {

   @v = $_;
   @z = map split, @v;

   foreach my $mnz (@ar) {
      @resz = grep { $z[$_] eq $mnz } 0 .. $#z;
      $mz = @resz;
      $zs += $mz;
   }
}

foreach $sx (@ar) {
   print "Total no of $sx is: $zs\n";
}

我期望的输出是

Total no of one is: 6
Total no of two is: 4
Total no of three is: 1
Total no of four is: 5

如果我只计算一个值,我的程序就可以正常工作,例如@ar = qw(one)。但我想立刻得到所有的产出。我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

您应该在每个 Perl程序的顶部use strictuse warnings,并使用my尽可能接近第一个声明每个变量使用点。您还应该使用有意义的变量标识符。这两项措施都将极大地帮助您进行调试。

您只有一个计数变量$zs,因此一旦循环完成,就无法对每个值进行单独计数。

您可以在循环内打印每个计数,但是您需要将第一个循环放在第二个循环中。这是一个在保持基本技术的同时做到这一点的工作示例。

use strict;
use warnings;

my @a  = qw(one two three four);
my @b  = qw(one one two four four);
my @c  = qw(four two one one);
my @d  = qw(four);
my @f  = qw(one two);

my @ta = ("@a", "@b", "@c", "@d", "@f");
my @ar = qw(one two three four);

for my $mnz (@ar) {

  my $zs;

  for (@ta) {
    my @z = grep { $_ eq $mnz } split;
    $zs += @z;
  }

  print "Total no of $mnz is: $zs\n";
}

<强>输出

Total no of one is: 6
Total no of two is: 4
Total no of three is: 1
Total no of four is: 5

但这远非理想的解决方案。每当您发现自己将数据分成类别时,您应该考虑使用哈希。目前还不清楚你是否需要@ta@az数组来完成除此任务之外的其他任务,但这里有更多Perlish方式来编写整个事物

use strict;
use warnings;

my @lista = qw(one two three four);
my @listb = qw(one one two four four);
my @listc = qw(four two one one);
my @listd = qw(four);
my @listf = qw(one two);

my @lists = \( @lista, @listb, @listc, @listd, @listf ); 

my %counts;

++$counts{$_} for map @$_, @lists;
print "Total no of $_ is: $counts{$_}\n" for keys %counts;

<强>输出

Total no of two is: 4
Total no of four is: 5
Total no of three is: 1
Total no of one is: 6
相关问题