【问题标题】:Sorting array of dates and returning the index in perl [closed]对日期数组进行排序并在perl中返回索引[关闭]
【发布时间】:2014-05-23 04:07:48
【问题描述】:

我有一个日期数组

@dates = qw(2/1/1989 2/1/1970 2/1/1970 2/1/1989 6/1/1970 12/1/1970);

我需要将它从最旧到最新排序,并在排序后返回未排序数组的索引。

输出应该是这样的

#sorted array
2/1/1970
2/1/1970
6/1/1970
12/1/1970
2/1/1989
2/1/1989

#indexes
1 2 4 5 0 3

【问题讨论】:

  • 欢迎来到 Stackoverflow。到目前为止,您尝试过什么?
  • 这些是国际日期还是北美日期?

标签: arrays perl sorting date indexing


【解决方案1】:
my @dates = qw(2/1/1989 2/1/1970 2/1/1970 2/1/1989 6/1/1970 12/1/1970);

my @idx = map $_->[0],
  sort {
    # compare years
    $a->[3] <=> $b->[3] ||
    # compare months
    $a->[1] <=> $b->[1] ||
    # compare days
    $a->[2] <=> $b->[2] ||
    # compare index for stable sort for duplicate values
    $a->[0] <=> $b->[0] 
  }
  map [$_, split /\D/, $dates[$_] ],
  0 .. $#dates;

print "indexes @idx\n";
# sorted values
print "$_\n" for @dates[@idx];

输出

indexes 1 2 4 5 0 3
2/1/1970
2/1/1970
6/1/1970    
12/1/1970
2/1/1989
2/1/1989

【讨论】:

    【解决方案2】:

    使用Time::PieceSchwartzian Transform

    use strict;
    use warnings;
    
    use Time::Piece;
    
    my @dates = qw(2/1/1989 2/1/1970 2/1/1970 2/1/1989 6/1/1970 12/1/1970);
    
    my @idx = map { $_->[0] }
        sort { $a->[1] <=> $b->[1] }
        map { [$_, Time::Piece->strptime($dates[$_], '%m/%d/%Y') ] }
        (0..$#dates);
    
    print "Indexes: @idx\n";
    
    print "Dates: @dates[@idx]\n";
    

    输出:

    Indexes: 1 2 4 5 0 3
    Dates: 2/1/1970 2/1/1970 6/1/1970 12/1/1970 2/1/1989 2/1/1989
    

    也可以执行以下操作:

    my @idx = sort { 
        Time::Piece->strptime($dates[$a], '%m/%d/%Y') <=> Time::Piece->strptime($dates[$b], '%m/%d/%Y')
    } (0..$#dates);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-13
      • 2018-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-28
      • 2017-11-02
      • 2014-01-04
      相关资源
      最近更新 更多