Perl推入排序数组

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

考虑下面的数据块,我如何维护第3个字段对数组进行排序,并继续推送项目?

$VAR1 = [
          '1111',
          'http://...',
           3       #this is one of the 3rd field mentioned above
        ];
$VARN = [
           '5555',
           'http://...',
            0
        ];

我的代码看起来像:

my @curItem = ($item->{id}, $item->{href}, getTotal( $item->{id}) );
push @items, \@curItem;

我发现this模块与我需要的类似。

任何帮助赞赏。

arrays perl sorting
3个回答
8
投票

您可以使用该模块,只需提供排序:

tie @a, "Tie::Array::Sorted", sub { $_[0]->[2] <=> $_[1]->[2] };

(或者沿着这些方向的东西......我将不得不检查它。基本上,你需要根据你传入的数组ref的元素进行排序)

编辑:是的,这适用于您的数据。刚检查一下:

use Tie::Array::Sorted;

tie @a, "Tie::Array::Sorted", sub { $_[0]->[2] <=> $_[1]->[2] };

push @a, [ "1111", "http:// ...", 3];
push @a, [ "5555", "http:// ...", 0];

foreach $ref (@a)
{
    print $ref . "\n";
    print "@$ref \n";
}

输出:

ARRAY(0x9130888)
5555 http:// ... 0
ARRAY(0x90dd818)
1111 http:// ... 3

3
投票

好吧,无论如何,push都会将项目附加到列表的末尾。这是一个堆栈操作。我会说你最好不要使用不同的数据结构,例如哈希,然后只在必要时按键或值排序。如果没有你想写的更多细节,很难说。

否则,您需要编写一个子程序,在列表中搜索最佳插入位置,然后使用splice将项目注入到位。这听起来更像你想要做的,但我不确定它会特别有效,因为每次你想要在保持排序顺序的同时添加项目时必须搜索列表中的插入点。


1
投票

如果要向@items添加多个数组引用,请先添加引用,然后使用Schwartzian Transform执行单个排序操作:

@items = map $_->[1], sort { $a->[0] <=> $b->[0] } map { [ $_->[2], $_ ] } @items;

兰德尔写了一篇专栏文章:http://www.stonehenge.com/merlyn/UnixReview/col64.html

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