Perl 计算一组数组中元素的出现次数
如何计算数组中特定值的出现次数 我的Perl代码Perl 计算一组数组中元素的出现次数,perl,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 = $_;
@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)
,那么我的程序运行良好。但我希望所有的输出同时完成。如何做到这一点?您应该在编写的每个Perl程序的顶部使用strict和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
Total no of two is: 4
Total no of four is: 5
Total no of three is: 1
Total no of one is: 6
但这远不是一个理想的解决方案。每当您发现自己将数据划分为多个类别时,都应该考虑使用哈希。除了这个任务之外,还不清楚是否需要@ta
和@az
数组,但是这里有一个更完善的方法来编写整个任务
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 one is: 6
Total no of two is: 4
Total no of three is: 1
Total no of four is: 5
Total no of two is: 4
Total no of four is: 5
Total no of three is: 1
Total no of one is: 6
对另一个for循环中的变量执行加法
+=
。您希望它如何保留单个值?您应该为此使用哈希:$hash{$word}++你应该学会使用严格使用;使用警告代码>为您节省一些调试时间。谢谢您。”print“给出输出,那么为什么要使用“printf”来打印语句?@user3902011:因为我开始使用printf
,改变了主意,但忘了更改调用!我已经修好了。谢谢