V
V
V Federoff2016-09-19 11:12:44
Perl
V Federoff, 2016-09-19 11:12:44

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

and for the mark student from ClassA2 it is:
ClassA2,mark,philosophy.5
+
ClassA2.mark,chemistry,4
= 9/2 = 4.5

I will be glad to your advice. Thank you.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
pcdesign, 2016-09-19
@pcdesign

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";
}

Result:
ClassA1-julia3.5
ClassA2-julia3.5
ClassA2-mark4.5
ClassA1-mark5

Although you can write all this prettier and shorter.

P
parserpro, 2016-09-29
@parserpro

I smell a programming assignment.
Come on yourself.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question