-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 に答える