在Perl中,如何按值的频率排序? [英] In Perl, how do I sort by frequency of a value?

查看:145
本文介绍了在Perl中,如何按值的频率排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个程序来计算数据文件列中出现的不同值。所以,如果列的可能值是A,B,C,就会是这样的。输出是像

I am trying to create a program to count the different values that occur in a column of a data file. So, it would be something like, if the possible values of a column are A, B, C. The output is something like

A   456
B   234
C   344

A,B和C的运行计数。

I have been able to get the running counts of A, B and C easily by doing something like this

my %count; 
for my $f (@ffile) {

    open F, $f || die "Cannot open $f: $!";

    while (<F>) {
       chomp;
       my @U = split / /;

       $count{$U[2]}++; 
    }

}
   foreach my $w (sort keys %count) {
         printf $w\t$count{$w};
     }

例如这里我计算文件的第二列。

For instance here I am counting the second column of the file in the path given.

如何通过计数而不是键(或值A,B,C)对printf的输出进行排序 -

How do I sort the output of the printf by the counts rather than the keys (or values A, B, C) to get -

A   456
C   344
B   234


推荐答案

for my $w (sort {$count{$b} <=> $count{$a}} keys %count) {
    print "$w\t$count{$w}\n";
}

这篇关于在Perl中,如何按值的频率排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆