如何计算重复键并将重复键的所有值加在一起以生成具有非重复键的新哈希?

发布于 2024-12-15 11:12:38 字数 701 浏览 1 评论 0原文

您好,我是 Perl 新手,处于初学者阶段,请帮助 我有一个散列,

%hash = { a => 2 , b=>6, a=>4, f=>2, b=>1, a=>1}

我想要输出为

  • a 3 次
  • b 2 次
  • f 1 次

新的散列应该是

%newhash = { a => 7, b=>7,f =>2}

我该怎么做?

为了计算哈希中键的频率,我正在做

foreach $element(sort keys %hash) {
    my $count = grep /$element/, sort keys %hash;
    print "$element comes in $count times \n";
}

但是通过这样做,我得到的输出为:

a comes 1 times 
b comes 1 times 
a comes 1 times
f comes 1 times 
b comes 1 times
a comes 1 times

这不是我想要的。

如何获得重复键的正确频率?如何添加这些重复键的值并存储在新的哈希中?

Hi I am new to perl and in a beginners stage Please Help
I am having a hash

%hash = { a => 2 , b=>6, a=>4, f=>2, b=>1, a=>1}

I want output as

  • a comes 3 times
  • b comes 2 times
  • f comes 1 time

a new hash should be

%newhash = { a => 7, b=>7,f =>2}

How can I do this?

To count the frequency of keys in hash i am doing

foreach $element(sort keys %hash) {
    my $count = grep /$element/, sort keys %hash;
    print "$element comes in $count times \n";
}

But by doing this I am getting the output as:

a comes 1 times 
b comes 1 times 
a comes 1 times
f comes 1 times 
b comes 1 times
a comes 1 times

Which is not what I want.

How can I get the correct number of frequency of the duplicate keys? How can I add the values of those duplicate key and store in a new hash?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

心在旅行 2024-12-22 11:12:38

根据定义,哈希值中不能多次包含相同的哈希键。您可能希望将初始数据存储在不同的数据结构中,例如二维数组:

use strict;
use warnings;
use Data::Dumper;

my @data = ( [ a => 2 ], 
             [ b => 6 ],
             [ a => 4 ],
             [ f => 2 ], 
             [ b => 1 ],
             [ a => 1 ],
           );
my %results;

for my $value (@data) {
  $results{$value->[0]} += $value->[1];
}

print Dumper %results;

# $VAR1 = 'a';
# $VAR2 = 7;
# $VAR3 = 'b';
# $VAR4 = 7;
# $VAR5 = 'f';
# $VAR6 = 2;

也就是说,其他错误的事情:

%hash = { a => 2 , b=>6, a=>4, f=>2, b=>1, a=>1}

您不能这样做,它正在分配一个 hashref ({} ) 到哈希值。使用 %hash = ( ... )$hashref = { ... }

By definition, a hash can not have the same hash key in it multiple times. You probably want to store your initial data in a different data structure, such as a two-dimensional array:

use strict;
use warnings;
use Data::Dumper;

my @data = ( [ a => 2 ], 
             [ b => 6 ],
             [ a => 4 ],
             [ f => 2 ], 
             [ b => 1 ],
             [ a => 1 ],
           );
my %results;

for my $value (@data) {
  $results{$value->[0]} += $value->[1];
}

print Dumper %results;

# $VAR1 = 'a';
# $VAR2 = 7;
# $VAR3 = 'b';
# $VAR4 = 7;
# $VAR5 = 'f';
# $VAR6 = 2;

That said, other wrong things:

%hash = { a => 2 , b=>6, a=>4, f=>2, b=>1, a=>1}

You can't do this, it's assigning a hashref ({}) to a hash. Either use %hash = ( ... ) or $hashref = { ... }.

橘虞初梦 2024-12-22 11:12:38

Sonam:

我重新编辑了您的帖子,以帮助调整其格式以供阅读。研究 Markdown 编辑帮助指南,这将使您的帖子更清晰、更容易理解。这里有一些提示:

  • 将代码缩进四个空格。这告诉 Markdown 不要管它,不要重新格式化它。
  • 当你列一个清单时,在前面加一个空格。 Markdown 理解它是一个项目符号列表并按此格式设置它。

在您的原始帖子上按“编辑”,您可以看到我所做的更改。


现在开始你的帖子。我不确定我是否理解您的数据。如果您的数据位于哈希中,则键将是唯一的。哈希中不能有重复的键,那么您的数据来自哪里?

例如,如果您从每行有两个数字的文件中读取它,您可以这样做:

use autodie;
use strict;
use warnings;

open (my $data_fh, "<", "$fileName");
my %hash;
while (my $line = <$data_fh>) {
   chomp $line;
   my ($key, $value) = split /\s+/, $line;
   $hash{$key}++;
}
foreach my $key (sort keys %hash) {
    print "$key appears $hash{$key} times\n";
}

前三行是 Perl 编译指示。它们改变了 Perl 的操作方式:

  • use autodie:这告诉程序在某些情况下终止,例如当您尝试打开一个不存在的文件时。这样,我就不必检查 open 语句是否有效。
  • use strict:这确保您必须在使用变量之前声明它们,这有助于消除 90% 的 Perl 错误。 大部分时间使用 my 声明变量。最后在声明它们的块中使用 my 声明的变量。这就是为什么 my %hash 必须在 while 块之前声明。否则,一旦循环完成,变量将变得未定义。
  • 使用警告:这让 Perl 在某些条件下生成警告。例如,您尝试打印出没有用户设置值的变量。

第一个循环只是逐行遍历我的数据并计算您的密钥出现的次数。第二个循环打印出结果。

Sonam:

I've reedited your post in order to help format it for reading. Study the Markdown Editing Help Guide and that'll make your posts clearer and easier to understand. Here are a couple of hints:

  • Indent your code by four spaces. That tells Markdown to leave it alone and don't reformat it.
  • When you make a list, put astricks with a space in front. Markdown understands it's a bulleted list and formats it as such.

Press "Edit" on your original post, and you can see what changes I made.


Now on to your post. I'm not sure I understand your data. If your data was in a hash, the keys would be unique. You can't have duplicate keys in a hash, so where is your data coming from?

For example, if you're reading it in from a file with two numbers on each line, you could do this:

use autodie;
use strict;
use warnings;

open (my $data_fh, "<", "$fileName");
my %hash;
while (my $line = <$data_fh>) {
   chomp $line;
   my ($key, $value) = split /\s+/, $line;
   $hash{$key}++;
}
foreach my $key (sort keys %hash) {
    print "$key appears $hash{$key} times\n";
}

The first three lines are Perl pragmas. They change the way Perl operates:

  • use autodie: This tells the program to die in certain circumstances such as when you try to open a file that doesn't exist. This way, I didn't have to check to see if the open statement worked or not.
  • use strict: This makes sure you have to declare your variables before using them which helps eliminate 90% of Perl bugs. You declare a variable most of the time using my. Variables declared with my last in the block where they were declared. That's why my %hash had to be declared before the while block. Otherwise, the variable would become undefined once that loops completes.
  • use warnings: This has Perl generate warnings in certain conditions. For example, you attempt to print out a variable that has no user set value.

The first loop simply goes line by line through my data and counts the number of occurrences of your key. The second loop prints out the results.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文