如何维护我添加到Perl哈希的键的顺序?

问题描述 投票:20回答:7

如何在使用以下程序中的哈希计算实际列表的顺序后维护实际列表的顺序?例如,<DATA>

a
b
e
a
c 
d 
a
c
d
b
etc.

使用哈希,我计算每个元素的出现次数。

我想要的是:

a  3
b  2
e  1
c  2
d  2

但是以下程序显示了我的情况。

my (%count, $line, @array_1, @array_2);
while ($line = <DATA>) {
    $count{$line}++ if ( $line =~ /\S/ );
}
@array_1 = keys(%count);
@array_2 = values(%count);
for(my $i=0; $i<$#array_1; $i++)
{
   print "$array_1[$i]\t $array_2[$i]";
}
perl data-structures hash perl-data-structures
7个回答
34
投票

哈希没有订购,但像往常一样,CPAN提供了一个解决方案:Tie::IxHash

use Tie::IxHash;
my %count;
tie %count, 'Tie::IxHash';

while ($line = <DATA>) {
$count{$line}++ if ( $line =~ /\S/ );
}

while( my( $key, $value)= each %count) {
    print "$key\t $value"; 
}

15
投票

散列表中的数据按密钥的散列码的顺序存储,对于大多数目的而言,其类似于随机顺序。您还希望存储每个键的第一个外观的顺序。这是解决此问题的一种方法:

my (%count, $line, @display_order);
while ($line = <DATA>) {
    chomp $line;           # strip the \n off the end of $line
    if ($line =~ /\S/) {
        if ($count{$line}++ == 0) {
            # this is the first time we have seen the key "$line"
            push @display_order, $line;
        }
    }
}

# now @display_order holds the keys of %count, in the order of first appearance
foreach my $key (@display_order)
{
    print "$key\t $count{$key}\n";
}

10
投票

perlfaq4回答"How can I make my hash remember the order I put elements into it?"


如何让哈希记住我将元素放入其中的顺序?

使用CPAN中的Tie :: IxHash。

use Tie::IxHash;

tie my %myhash, 'Tie::IxHash';

for (my $i=0; $i<20; $i++) {
    $myhash{$i} = 2*$i;
    }

my @keys = keys %myhash;
# @keys = (0,1,2,3,...)

6
投票

只是:

my (%count, @order);
while(<DATA>) {
  chomp;
  push @order, $_ unless $count{$_}++;
}
print "$_ $count{$_}\n" for @order;
__DATA__
a
b
e
a
c
d
a
c
d
b

或者作为一个班轮

perl -nlE'$c{$_}++or$o[@o]=$_}{say"$_ $c{$_}"for@o'<<<$'a\nb\ne\na\nc\nd\na\nc\nd\nb'

5
投票

另一种选择是David Golden的(@xdg)简单的纯perl Hash::Ordered模块。您获得了顺序,但它更慢,因为哈希成为幕后的对象,您使用方法来访问和修改哈希元素。

可能的基准测试可以量化模块比常规哈希值慢多少,但它是一种很酷的方式,可以在小脚本中使用键/值数据结构,并且在这种应用程序中足够快。该文档还提到了其他几种排序哈希的方法。


4
投票

我不相信这总是一种更好的技术,但我有时会用它。它可以存储注意到的计数和顺序,而不仅仅是具有“看见”类型的哈希。

基本上,而不是$count{$line}有多少次看到,$count{$line}{count}是看到的时间,$count{$line}{order}是它被看到的顺序。

my %count;
while (my $line = <DATA>) {
    chomp $line;
    if ($line =~ /\S/) {
        $count{$line} ||= { order => scalar(keys(%count)) };
        $count{$line}{count}++;
    }
}

for my $line (sort { $count{$a}{order} <=> $count{$b}{order} } keys %count ) {
    print "$line $count{$line}{count}\n";
}

1
投票

散列只是数组,直到它们在Perl中赋值,因此如果将其转换为数组,则可以按原始顺序迭代它:

my @array = ( z => 6,
              a => 8,
              b => 4 );

for (my $i=0; $ar[$i]; ++$i) {
    next if $i % 2;
    my $key = $ar[$i];
    my $val = $ar[$i+1];

    say "$key: $val"; # in original order
}

如果你明显这样做,你就失去了哈希索引的好处。但由于哈希只是一个数组,因此只需将数组赋值给哈希即可创建一个数组:

my %hash = @array;
say $hash{z};

这可能只是“使用数组作为索引”解决方案的变体,但我认为它更整洁,因为不是手动(或以其他方式)键入索引,而是直接从源数组创建它。

© www.soinside.com 2019 - 2024. All rights reserved.