arrays - 散列的散列 : How to get the number of occurrences of a key?

标签 arrays perl hash

我有以下文本文件。

foo1    bam
foo1    bam
foo2    bam
foo1    zip
foo2    boo
foo1    zip
foo3    zip

我想制作一个哈希散列,其中 KEY1 是 第一列 , KEY2 是它发出的声音( 第二列 ): bamzipboo ,而 VALUE 是 _rstrong 出现的次数.这样数据结构是这样的:
$VAR1 = {
      'foo1' => {
                         'bam' => [
                                    2
                                  ],
                         'zip' => [
                                  2
                                ],
                       },
      'foo2' => {
                        'bam' => [
                                 1
                               ],
                        'boo' => [
                                 1
                               ],
                      },
        'foo3' => {
                        'zip' => [
                                  1
                                ],
                    }
         }

这是我到目前为止所拥有的
use strict; use warnings;    
open(my $fh, '<', 'file.txt') or die $!;
my %HoH;
while(<$fh>){
    chomp;
    my @cols = split(/\t/, $_);
    my $KEY1 = $cols[0];
    my $KEY2 = $cols[1];
    push( @{$HoH{$KEY1}{$KEY2}}, 1); # This actually creates a hash of hash of arrays
}

my %HoH_final;
foreach my $KEY1 (%HoH) {
    foreach my $KEY2 (keys %HoH{$KEY1}){
    my $count = scalar @{$HoH{$KEY1}{$KEY2}}; # get the size of that array
        push( @{$HoH_final{$KEY1}{$KEY2}}, $count);
   }
}

你怎么看?

最佳答案

你真的不想要下面的数据结构吗?

{
   'foo1' => {
      'bam' => 2,
      'zip' => 2,
   },
   ...
}

如果是这样的话,
while (<$fh>) {
    chomp;
    my @cols = split /\t/;
    ++$HoH{ $cols[0] }{ $cols[1] };
}

如果你真的想要单元素数组,
while (<$fh>) {
    chomp;
    my @cols = split /\t/;
    ++$HoH{ $cols[0] }{ $cols[1] }[0];
}

关于arrays - 散列的散列 : How to get the number of occurrences of a key?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16127384/

相关文章:

c# - 如何在 C# 中使用三重 DES 执行 ISO 9797-1 MAC?

c# - String.join 来自最后一个元素的数组

perl - 如何让 grep 使用 "from X to Y"语法? (使用日期作为参数)

javascript - 将js数组分为2个部分

perl - 脚本的输出何时附加到文件中,我可以采取什么措施来避免结果?

regex - Perl调用正则表达式替换中的tr函数

c++ - 确定性地生成加密安全 key 和 IVEC

c++ - MD5 散列时填充字符串

c - 在C中交换数组内的奇数和偶数

javascript - 如何更改数组字符串中特定单词的颜色? : Javascript/jQuery