gpt4 book ai didi

algorithm - 在 Perl 中更改键时汇总总数

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:44:41 24 4
gpt4 key购买 nike

我有一个具有以下格式的输入文件

ant,1
bat,1
bat,2
cat,4
cat,1
cat,2
dog,4

我需要为每个键(第 1 列)聚合 col2,所以结果是:

ant,1
bat,3
cat,7
dog,4

其他注意事项:

  1. 假设输入文件已排序
  2. 输入文件比较大(1M行左右),不想用数组占内存
  3. 每一行输入都应在我们阅读时进行处理,并移至下一行
  4. 我需要将结果写入 outFile
  5. 我需要在 Perl 中执行此操作,但伪代码或算法同样有用

谢谢!

这是我想出的...想看看这是否可以写得更好/更优雅。

open infile, outFile

prev_line = <infile>;
print_line = $prev_line;

while(<>){
curr_line = $_;

@prev_cols=split(',', $prev_line);
@curr_cols=split(',', $curr_line);

if ( $prev_cols[0] eq $curr_cols[0] ){
$prev_cols[1] += curr_cols[1];
$print_line = "$prev_cols[0],$prev_cols[1]\n";
$print_flag = 0;
}
else{
$print outFile "$print_line";
$print_flag = 1;
$print_line = $curr_line;
}
$prev_line = $curr_line;
}

if($print_flag = 1){
print outFile "$curr_line";
}
else{
print outFile "$print_line";
}

最佳答案

#!/usr/bin/perl
use warnings;
use strict;
use integer;

my %a;
while (<>) {
my ($animal, $n) = /^\s*(\S+)\s*,\s*(\S+)/;
$a{$animal} += $n if defined $n;
}
print "$_,${a{$_}}\n" for sort keys %a;

这段简短的代码让您有机会学习 Perl 出色的 hash 功能,如 %a。哈希是 Perl 的核心。没有它们,一个人真的无法写出流利的 Perl。

顺便观察一下,代码使用了 Perl 有趣的autovivification 功能。第一次在输入流中遇到特定动物时,不存在计数,因此 Perl 隐含地假定预先存在的计数为零。因此,+= 运算符不会失败,即使它看起来应该失败。它只是在第一个实例中加到零。

另一方面,可能发生的情况不仅是数据的数量,而且 动物的数量 都非常大,以至于人们不想存储散列 %a。在这种情况下,仍然可以计算总数,前提是数据在输入中按动物排序,就像在您的示例中一样。在这种情况下,像下面这样的东西可能适合(尽管遗憾的是它没有上面那么整洁)。

#!/usr/bin/perl
use warnings;
use strict;
use integer;

my $last_animal = undef;
my $total_for_the_last_animal = 0;

sub start_new_animal ($$) {
my $next_animal = shift;
my $n = shift;
print "$last_animal,$total_for_the_last_animal\n"
if defined $last_animal;
$last_animal = $next_animal;
$total_for_the_last_animal = $n;
}

while (<>) {
my ($animal, $n) = /^\s*(\S+)\s*,\s*(\S+)/;
if (
defined($n) && defined($animal) && defined($last_animal)
&& $animal eq $last_animal
) { $total_for_the_last_animal += $n; }
else { start_new_animal $animal, $n; }
}
start_new_animal undef, 0;

关于algorithm - 在 Perl 中更改键时汇总总数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10942018/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com