哈希如何用于查找唯一项目 [英] How is the hash used to find unique items

查看:44
本文介绍了哈希如何用于查找唯一项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我见过一个简单的程序.好吧,除了一件事我了解的洞程序,这就是 Hash 在这里的工作方式:

I have seen one easy program. Well, the hole program i have understand except one thing and that is how Hash is working here :

程序 ->从列表中提取唯一元素

Program ->Extracting Unique Elements from a List

@list = (20,30,40,60,40,20,30,2);
@uniq = ();
%seen = ();
foreach $item (@list) {
    unless ($seen{$item}) 
    {
        # if we get here, we have not seen it before
        push(@uniq, $item);
        $seen{$item}++;

    }
    print %seen;
    print"\n";
}

我的问题是哈希如何从其现有值与当前值进行比较,即它如何检查该值是否已经存在的天气.如果我正在打印 %seen 我得到了一些值.这些值是如何来的?

My question is how hash is comparing from its exiting value to current value i.e how it is checking weather that value is already there or not .If I m printing the %seen i am getting some value.how those values are coming ?

推荐答案

如果它使您更清楚,请更改

If it makes it clearer for your, change

if (!$seen{$item}) { $seen{$item}++; ... }

if (!exists($seen{$item})) { $seen{$item} = 1; ... }

第一次遇到特定项目时,它不作为哈希中的键存在,因此输入了 if.if 的主体在散列中创建一个与项目相等的键.

The first time you encounter a particular item, it doesn't exist as a key in the hash, so the if is entered. The body of the if creates a key in the hash equal to the item.

第二次(以及第三次和......)遇到特定项目时,它作为哈希中的一个键存在,因此没有输入 if.

The second (and third and ...) time you encounter a particular item, it exists as a key in the hash, so the if is not entered.

顺便说一句,

if (!$seen{$item}) { $seen{$item}++; ... }

可以缩短为

if (!$seen{$item}++) { ... }

my @uniq;
for my $item (@list) {
    push @uniq, $item if ...;
}

可以缩短为

my @uniq = grep ..., @list;

所以整件事可以写成

my @list = (20,30,40,60,40,20,30,2);
my %seen;
my @uniq = grep !$seen{$_}++, @list;

这篇关于哈希如何用于查找唯一项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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