【问题标题】:sort numbers numerically and strings alphabetically in an array perl在数组 perl 中按数字和字母顺序对数字进行排序
【发布时间】:2020-05-28 12:49:16
【问题描述】:

这是一个非常简单的问题,但我无法解决。我有一个数组

@arr = qw(txt text anothertext 38.09 100.87 0.876)

如何按数字对数组中的数字和按字母顺序对字符串进行排序。所以输出看起来像:

@sorted_as = (anothertext text txt 100.87 38.09 0.876)

或者,

@sorted_des = (txt text anothertext 100.87 38.09 0.876)

抱歉,如果我重复了任何问题但找不到合适的答案。

【问题讨论】:

  • 不应该@sorted_as = (anothertext text txt 0.876 38.09 100.87) 吗?我假设_as 表示升序。

标签: perl sorting numeric alphabetical-sort


【解决方案1】:

分成 2 个列表,分别对每个列表进行排序,然后组合回 1 个列表。

use warnings;
use strict;

my @arr = qw(txt text anothertext 38.09 100.87 0.876);

my @word =         sort {$a cmp $b} grep {  /^[a-z]/i } @arr;
my @num  = reverse sort {$a <=> $b} grep { !/^[a-z]/i } @arr;
my @sorted_as = (@word, @num);
print "@sorted_as\n";

输出:

anothertext text txt 100.87 38.09 0.876

要同时获取 des,请添加以下行:

@word = reverse @word;
my @sorted_des = (@word, @num);
print "@sorted_des\n";

【讨论】:

  • 如果我的数组实际上是一个哈希数组,我该如何调整它?目前我有sort { $b-&gt;{$key} cmp $a-&gt;{$key} } @array_of_hashes
  • @tt_pre 然后只需在@toolic 的答案中的两个排序块中将$a 替换为$a-&gt;{$key} 和$b。您还需要 grep {$$_{$key}=~/^[a-z]/i} 和另一个 = 变为 ! 的。
【解决方案2】:

使用Sort::Key::Multi

# urns = (u)nsigned int, (r)everse (n)umber, (s)tring
use Sort::Key::Multi qw( urnskeysort );

my @sorted =
   urnskeysort {
      /^[0-9]/
         ? ( 1, $_, "" )
         : ( 0, 0, $_ )
   }
      @unsorted;

同样,您可以使用urnrskeysort 进行第二次订购。

【讨论】:

  • 抱歉不能使用包。本机 perl 5.18 的任何解决方案?
  • 这应该很容易适应sort,尤其是当您将它用作Schwartzian Transform的一部分时
猜你喜欢
  • 2020-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-19
相关资源
最近更新 更多