开发者

How can I sum array values by unique key?

开发者 https://www.devze.com 2022-12-24 04:44 出处:网络
开发者_如何学PythonFor example array ( product1_quantity => 5, product1_quantity => 1, product2_quantity => 3,
开发者_如何学Python

For example

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

with result:

product1_quantity - 6, 
product2_quantity - 10, 
product3_quantity - 2

Thanx!


sorry, guys

stupid example, instead this really

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

?


Pull items off two at a time, and add to hash.

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;
}


You'd want something similar to:

  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;

This spits out:

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

Be warned though -- if you've got any undefs in your quantity values this is going to break hard. You need to have an even numbered length array of product/numeric quantity pairs.


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 will contain the sums


In 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;

Output is:

product2_quantity - 10,
product3_quantity - 2,
product1_quantity - 6

The order is different, but you could force it to be "in order" by adding sorting:

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

精彩评论

暂无评论...
验证码 换一张
取 消