如何按值的频率排序?
我正在尝试创建一个程序来计算数据文件列中出现的不同值。所以,如果一列的可能值是 A、B、C,那么输出就像
A 456
B 234
C 344
我已经能够通过执行类似的操作轻松获得 A、B 和 C 的运行计数
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};
}
例如这里我正在计算给定路径中文件的第二列。
如何按计数而不是键(或值 A、B、C)对 printf 的输出进行排序以获得以下输出?
A 456
C 344
B 234
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是常见问题解答:
perldoc -q 排序
输出:
This is a FAQ:
perldoc -q sort
Output:
一些补充意见:
,如果您粘贴实际代码(尽可能缩写),您将帮助我们帮助您。
当人们重新创建实际代码时,他们经常掩盖或忽略问题的根源。
这会分割空格字符并查找第二个空格之后的计数;它通常更容易做到:
split
与常量空格一起使用,而不是使用正则表达式在任何空格序列上进行拆分,就像split /\s+/
一样,只不过它忽略尾随空格。 ..这是一件很常见的事情,因此有一种特殊的语法。请注意,咀嚼变得不必要了。Some additional comments:
You help us help you if you paste your actual code, abbreviated where possible.
When people recreate their actual code, they often obscure or omit the very source of their problem.
This splits on space characters and looks for the count after the second space; it's often easier to do:
split
used with a constant space instead of a regex splits on any sequence of whitespace, likesplit /\s+/
except that it ignores trailing whitespace...this is a common enough thing to do that there is this special syntax for it. Note that the chomp becomes unnecessary.