perl - 数组中有重复项的数学 [英] perl - Math with duplicate entries in array

查看:32
本文介绍了perl - 数组中有重复项的数学的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数组:

my @name = (bob, bob, dave, john, john, mary, mary, mary);
my @cost = (5, 7, 4, 4, 4, 6, 3 , 4);

我想将它们映射在一起,这样输出就是:

I want to map them together so the output would just be:

bob 12
dave 4
john 8
mary 13

虽然数组发生了变化,所以我不能使用引用.如何将 @cost@name 分组并添加 @cost 的值?

The array's change though so I can't use references. How do I group @cost by @name and add the values of @cost?

推荐答案

我会尝试这样的事情.

#!/usr/bin/perl 
use strict; use warnings; use Data::Dumper;
my @name = qw(bob bob dave john john mary mary mary);
my @cost = qw(5 7 4 4 4 6 3 4);
my %seen = ();
foreach(0..scalar(@name)-1){
    if (!exists $seen{$name[$_]}){
        $seen{$name[$_]} = $cost[$_];
    }
    else{
        my $sum = 0;
        $sum = $seen{$name[$_]};
        my $new = $sum + $cost[$_];
        $seen{$name[$_]} = $new;
    }
}
print Dumper(\%seen);

输出:

$VAR1 = {
    'bob' => 12,
    'john' => 8,
    'dave' => 4,
    'mary' => 13
};

这篇关于perl - 数组中有重复项的数学的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆