Answer the question
In order to leave comments, you need to log in
The task of processing a CSV file. How to calculate the average value?
I have an unsorted CSV file with the following content:
ClassA1,mark,chemistry,5
ClassA2,mark,philosofy.5
ClassA2,julia,physic,5
ClassA1,julia,math,3
ClassA1,mark,philosophy, 5
ClassA1,julia,chemistry,4
ClassA2.mark,chemistry,4
ClassA2,julia,literature,2
...
where Can you tell me $класс,$имя_ученика,$предмет,$оценка
how best to calculate the average score in all subjects for all students of different classes using a perl script? For example, for the mark student from the ClassA1 class, this is:
ClassA1,mark,chemistry,5
+
ClassA1,mark,philosophy, 5
=
10/2 =5
ClassA2,mark,philosophy.5
+
ClassA2.mark,chemistry,4
= 9/2 = 4.5
Answer the question
In order to leave comments, you need to log in
If on the knee and without using any modules, then you can do this:
use strict;
use warnings;
use utf8;
my $csv = <<'EOF';
ClassA1,mark,chemistry,5
ClassA2,mark,philosofyr,5
ClassA2,julia,physic,5
ClassA1,julia,math,3
ClassA1,mark,philosophy,5
ClassA1,julia,chemistry,4
ClassA2,mark,chemistry,4
ClassA2,julia,literature,2
EOF
my @csv = split "\n", $csv;
my (%sum, %count);
for my $row (@csv) {
my ( $class, $name, undef, $num ) = split ",", $row;
my $key = $class . '-' . $name;
$sum{$key} += $num;
$count{$key} += 1;
}
for my $name_class ( keys %sum ) {
print $name_class, $sum{$name_class}/$count{$name_class}, "\n";
}
ClassA1-julia3.5
ClassA2-julia3.5
ClassA2-mark4.5
ClassA1-mark5
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question