我有一个数据集将有很多列。我需要做的是将某个列的总和与另一个列相加。举个例子,
ID Volume
A 20
D 60
B 10
A 50
K 30
B 100
D 80
所以我想要所有不同ID(A,B,C ...)的合计总和,并按总和排序
结果就像
D 140
B 110
A 70
K 30
我将如何在perl中完成此任务?
最佳答案
#!/usr/bin/perl
use strict;
use warnings;
my %ids_and_sums;
while (<>) {
# The regex will only consider one single uppercase letter as
# an ID; in case your IDs may look different, you could prepend
# your 'ID Volume' line with a character which will never be part
# of an ID, and modify below regex to meet your needs
my ($id, $volume) = m/^([A-Z])\s+(\d+)/;
if ($id and $volume) {
$ids_and_sums{$id} += $volume;
}
}
foreach my $key (sort {$ids_and_sums{$b} <=> $ids_and_sums{$a}} keys %ids_and_sums) {
print "$key: $ids_and_sums{$key}\n";
}
打印:
D: 140
B: 110
A: 70
K: 30
编辑:我修改了代码,以便排序以总和的降序排列。
关于perl - Perl计算一列加另一列的总和,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4545989/