gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 22:32:59 24 4
gpt4 key购买 nike

我有以下文本文件。

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/

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