如何通过唯一键对数组值求和?

时间:2010-03-24 16:10:39

标签: perl

例如

array (
product1_quantity => 5,
product1_quantity => 1,
product2_quantity => 3,
product2_quantity => 7,
product3_quantity => 2,
)

结果:

product1_quantity - 6, 
product2_quantity - 10, 
product3_quantity - 2

感谢名单!


抱歉,伙计们

愚蠢的例子,而不是真的

数组([0] =>数组([product1] => 7) [1] =>数组([product1] => 2) [2] =>数组([product2] => 3) )

4 个答案:

答案 0 :(得分:3)

一次拉出两个项目,然后添加到哈希。

my @array = (
        product1_quantity => 5,
        product1_quantity => 1,
        product2_quantity => 3,
        product2_quantity => 7,
        product3_quantity => 2,
);
my %sums;
while (@array and my ($k,$v) = (shift(@array),shift(@array)) ) {
        $sums{$k} += $v;
}

答案 1 :(得分:2)

你想要类似的东西:

  use Data::Dumper;
  my @input = ( product1_quantity => 5,
                product1_quantity => 1,
                product2_quantity => 3,
                product2_quantity => 7,
                product3_quantity => 2,
              );
  my %output;

  while (my $product = shift(@input) and my $quantity = shift(@input)) {
    $output{$product} += $quantity;
  }

  print Dumper %output;

这吐出来了:

$VAR1 = 'product2_quantity';
$VAR2 = 10;
$VAR3 = 'product3_quantity';
$VAR4 = 2;
$VAR5 = 'product1_quantity';
$VAR6 = 6;

请注意 - 如果你的数量值有任何未定数,这将会很难破解。您需要具有偶数编号的产品/数量对数组。

答案 2 :(得分:0)

new_array;
foreach p in array:
  if(new_array.contains(p.key))
    new_array[p.key] += p.value;
  else
    new_array[p.key] = p.value;

new_array将包含总和

答案 3 :(得分:0)

Perl:

my %hash = ();
$hash{'product1_quantity'} += 5;
$hash{'product1_quantity'} += 1;
$hash{'product2_quantity'} += 3;
$hash{'product2_quantity'} += 7;
$hash{'product3_quantity'} += 2;

say join ",\n", map { "$_ - $hash{$_}" } keys %hash;

输出是:

product2_quantity - 10,
product3_quantity - 2,
product1_quantity - 6

订单不同,但您可以通过添加排序强制它“按顺序”:

say join ",\n", map { "$_ - $hash{$_}" } sort {$a cmp $b} keys %hash;