簡體   English   中英

比較Perl中多個哈希值的鍵值

[英]Compare values of keys across multiple hashes in Perl

我有一組哈希(使用Tie :: IxHash保留鍵序列),我想比較每個鍵的值。 哈希數可以變化。 例如,我想計算為鍵“ 1”分配值“ 1”和“ 0”的次數。 我知道,如果我將哈希值放入一個哈希值數組中然后循環遍歷它們,應該有一種很好的快速方法來計算值匹配,但是我被卡住了,無法自行解決。

%hash1 = ( 1 => '1',
           2 => '1',
           3 => '0',
           4 => '0',
         );

%hash2 = ( 1 => '1',
           2 => '1',
           3 => '1',
           4 => '0',
         );

%hash3 = ( 1 => '1',
           2 => '1',
           3 => '0',
           4 => '1',
         );

%hash4 = ( 1 => '1',
           2 => '0',
           3 => '0',
           4 => '1',
         );

上面的預期結果是:

$key1: $agr1 = 4; $agr0 = 0;
$key2: $agr1 = 3; $agr0 = 1;
$key3: $agr1 = 1; $agr0 = 3;
$key4: $agr1 = 2; $agr0 = 2;

現在,我最終要做的是循環遍歷第一個哈希的鍵,然后將它們與其他每個哈希進行比較,由於明顯的原因,這很乏味又愚蠢。

謝謝你的幫助!

更正:我使用的是哈希,而不是哈希引用。 相應地編輯了上面的代碼。

您可以在@wanted中輸入任何所需的值,從而使結果具有一定的靈活性。 假設您的哈希實際上是哈希引用(在示例中是模糊的):

my @hashes = ($hash1,$hash2,$hash3,$hash4);
my %count;
for my $hash (@hashes) {
    $count{ $_ }{ $hash->{$_} }++ for keys %$hash;
}
my @wanted = (1,0);
for my $key (sort { $a <=> $b } keys %count) {
    my @result = map { "agr$_ = " . ($count{$key}{$_} || 0) . ';' } @wanted;
    print "key $key: @result\n";
}

輸出:

key 1: agr1 = 4; agr0 = 0;
key 2: agr1 = 3; agr0 = 1;
key 3: agr1 = 1; agr0 = 3;
key 4: agr1 = 2; agr0 = 2;

偽perl:

# Build a list of refs to your hashes
@a = { \%hash1, \%hash2, ... }

# A container to hold the keys and counts
$keys = {} 

# Initialize the key container
for my $h in @a
    for my $k in %$h
        $keys->{$k} = {0 => 0, 1 => 0} unless exists $keys->{$k}

# Iterate once over all the keys and count occurrences
# assumes input hash values can be only 0 or 1
for my $k in %$keys
    for my $h in @a
        $keys->{$k}->{$h->{$k}}++ if exists $h->{$k};

首先,您的哈希示例是錯誤的。 %hash = {}

如果您使用%符號,則需要() 如果您需要哈希引用, $hash = {}

回到您的問題。 你可以做這樣的事情。

通常稱為“可見”哈希。

# appending your example above....
my @arr = (\%hash1, \%hash2, \%hash3, \%hash4);
my $seen = {}; 

# iterate over each hash
for my $hash (@arr) {
    # iterate over each key in hash
    for my $k (keys %$hash) {
        my $val = $hash->{$k};

        # check $val and increment 
        if ($val) {
            $seen->{$k}{1}++;
        } else {
            $seen->{$k}{0}++;
        }   
    }   
}

for my $k ( sort keys %$seen ) { 
    # in case any value is 0/undef
    print "$k:  1 = "
      . ( $seen->{$k}->{0} ? $seen->{$k}->{0} : 0 ) . " 0 = "
      . ( $seen->{$k}->{0} ? $seen->{$k}->{0} : 0 ) . "\n";
}

哪些輸出:

$ perl test.pl
1:  1 = 0 0 = 0
2:  1 = 1 0 = 1
3:  1 = 3 0 = 3
4:  1 = 2 0 = 2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM