简体   繁体   English

如何对 hash 的元素求和?

[英]How to sum the elements of hash?

Hi I have a hash where the key is a 3digit code and value is number of elements under that code.嗨,我有一个 hash,其中键是 3 位代码,值是该代码下的元素数。 I want to sum the 3digit code and multiply with the number of elements, then finally add them up.我想将 3digit 代码相加并乘以元素的数量,然后最后将它们相加。 Example:例子:

000 23
012 42
222 34

[(0+0+0)*23]+[(0+1+2)*42]+[(2+2+2)*34]=0+126+204=330

so i tried所以我尝试了

foreach my $key (sort keys %hash ){      
@arrSum=split(//, $key);
   foreach $i (@arrSum){    
     $sum+=$i;
     $value=$sum*$hash{$key};
   }    
}

It does not work.这没用。 It actually has to consider each line, instead it sums up all the 3digit code at once.它实际上必须考虑每一行,而是一次总结所有 3 位代码。 Need some help.需要一些帮助。

Here is more functional approach to the problem, it also uses sum from List::Util :这是解决问题的更实用的方法,它还使用List::Util中的sum

use List::Util qw(sum);

my %hash = qw(
    000 23
    012 42
    222 34
);

print sum(map { sum(split //) * $hash{$_} } keys %hash);     # 330

I made a small change in your code, and I got the right value:我对您的代码做了一些小改动,得到了正确的值:

#!/usr/bin/perl

use strict;
use warnings;

my %hash = (
   "000" => 23,
   "012" => 42,
   "222" => 34,
);

my $value = 0;
for my $key (sort keys %hash )
{  
   my $sum = 0;
   my @arrSum = split(//, $key);
   for my $i (@arrSum)
   {    
     $sum += $i;
   }
   $value += $sum * $hash{$key};
}

print "$value\n";

(a+b+c)*d = (a*d)+(b*d)+(c*d), so you could do (a+b+c)*d = (a*d)+(b*d)+(c*d),所以你可以这样做

my $value;
for my $key (keys %hash) {      
   for my $digit (split(//, $key)) {
      $value += $digit * $hash{$key};
   }    
}

But it looks like you were trying for:但看起来你正在尝试:

my $value;
for my $key (keys %hash) {      
   my $sum;
   $sum += $_ for split(//, $key);
   $value += $sum * $hash{$key};
}

More or less the same:或多或少相同:

use List::Util qw( sum );

my $value;
for my $key (keys %hash) {      
   $value += sum(split(//, $key)) * $hash{$key};
}

This problem seems tailor-made for each :这个问题似乎是为每个人量身定做的:

#!/usr/bin/perl

use warnings; use strict;
use List::Util qw( sum );

my %hash = (
   "000" => 23,
   "012" => 42,
   "222" => 34,
);

my $total;
while ( my ($key, $val) = each %hash ) {
    $total += sum(split //, $key) * $val;
}

print "$total\n";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM