-2

我有以下哈希结构,哈希哈希。

$VAR1 = { '191' => { 'test1' => { 'score' => '9.18' }, 'test2' => { 'score' => '2.84' }, 
                     'test3' => { 'score' => '15.62' }, 'test4' => { 'score' => '11.84' }, 

          '190' => { 'test1'=> { 'score' => '13.28' }, 'test2' => { 'score' => '-47.56' }, 
                     'test3' => { 'score' => '18.50' }, 'test4' => { 'score' => '14.88' } } }

我正在尝试根据“分数”值对哈希进行排序。排序应该只发生在主键 '191' 和 '190' 内部的内容中。有关预期结果,请参见下面的哈希结构。

$VAR1 = { '191' => {'test3' => { 'score' => '15.62' }, 'test4' => { 'score' => '11.84' }
                    'test1' => { 'score' => '9.18' }, 'test2' => { 'score' => '2.84' }, 
                     
        ​ '190' => { 'test3' => { 'score' => '18.50' }, 'test4' => { 'score' => '14.88' }
                    'test1'=> {'score' => '13.28' }, 'test2' => { 'score' => '-47.56' } } }

排序是根据分数值降序进行的。

我已经尝试了下面的代码,但它有点基于主键。我需要输出,如预期的哈希结构所示。

my @sort_by_rank;
for my $key1 (keys %rankBased) {
    for my $key2 (keys %{$rankBased{$key1}}) {
        @sort_by_rank = sort{ $rankBased{$b}{$key2}{score} <=> $rankBased{$a}{$key2}{score}
                            } keys %rankBased;
    }   
}

这里 %rankBased 是哈希值。

请帮忙。

4

1 回答 1

3

您无法对哈希进行排序,但可以对哈希键的列表进行排序。

for my $student_id (keys %tests_by_student_id) {
   my $tests = $tests_by_student_id{$student_id};
   my @sorted_test_ids =
      sort { $tests->{$b}{score} <=> $tests->{$a}{score} }
         keys(%$tests);

   # Do something with the student's sorted tests here.
}

(无意义%rankBased重命名为%tests_by_student_id。)


上面的很棒是你想对每个学生做一些事情。但是,如果您真的想“对哈希进行排序”,则需要切换到不同的结构。

for my $student_id (keys %tests_by_student_id) {
   # This next line is the same as 
   # my $tests = $tests_by_student_id{$student_id};
   # except changing $tests also changes
   # $tests_by_student_id{$student_id}.
   for my $tests ($tests_by_student_id{$student_id}) {
      $tests = [
         sort { $b->{score} <=> $a->{score} }
            map { { id => $_, %{ $tests->{$_} } } }
               keys(%$tests)
      ];
   }
}

这产生

$VAR1 = {
   '191' => [ { id => 'test3', score =>  15.62 },
              { id => 'test4', score =>  11.84 },
              { id => 'test1', score =>   9.18 },
              { id => 'test2', score =>   2.84 } ],
   '190' => [ { id => 'test3', score =>  18.50 },
              { id => 'test4', score =>  14.88 },
              { id => 'test1', score =>  13.28 },
              { id => 'test2', score => -47.56 } ],
};
于 2021-03-06T20:06:38.127 回答