perl - 迭代具有数十亿行的文件,输出出现次数最多的行

标签 perl iteration

迭代包含多行国家/地区的文件并打印出出现次数最多的国家/地区的最佳算法/方法是什么?

每一行都是一个字符串,并且每行只包含一个国家/地区名称。

假设可能有 10 亿个不同的国家/地区。 (国家是一个坏例子)

United States
Iran
India
United States
China
Iran
....
....
Canada //1 billionth line

最佳答案

# Count the unique elements.
my %hash;
while(<>) {
    chomp;
    $hash{$_}++;
}

# Find the key with the largest value.
sub largest_value {
    my $hash = shift;

    my ($big_key, $big_val) = each %$hash;

    while (my ($key, $val) = each %$hash) {
        if ($val > $big_val) {
            $big_key = $key;
            $big_val = $val;
        }
    }

    return $big_key;
}

print largest_value(\%hash);

关于perl - 迭代具有数十亿行的文件,输出出现次数最多的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13852937/

相关文章:

perl - 在 Perl 中,如何在一个循环中读取多个文件句柄?

javascript - 如何在函数体中将 JavaScript 函数参数用作 jQuery 选择器?

arrays - 迭代时更新 golang 数组

arrays - 如何在 Perl 中创建二维数组?

c++ - 是否有 Perl 的 __DATA__ 段的 C++ 等价物(或等价技术)?

perl - Perl中的递归排序

python - 按类型有效地汇总项目

c# - 如何在跳过某些值的同时遍历枚举类型?

python - ElementTree : Element. remove() 跳跃迭代

python - 忽略 nan 值并执行 numpy.polyval 的函数