The file data.txt
contains the following:
1.00 1.23 54.4 213.2 3.4
The output of the scripts are supposed to be:
ave: 54.646
Some simple scripts are preferred.
To print mean values of all columns, assign totals to array @t: perl -lane 'for $c (0.. $#F){$t[$c] += $F[$c]}; END{for $c (0.. $#t){print $t[$c]/$.}}
Average is the sum of elements divided by the number of elements. Examples: Input : [4, 5, 1, 2, 9, 7, 10, 8] Output : Average of the list = 5.75 Explanation: Sum of the elements is 4+5+1+2+9+7+10+8 = 46 and total number of elements is 8.
with open ('abc.txt') as fh: sum = 0 numlines = 0 for line in fh: n = line.split (':') [-1] sum += float (n) numlines += 1 average = sum / numlines print average this might work, but is terribly unidiomatic in Python. Try to avoid using the str.find commands.
In this case, we have 3 numbers. That means that in order to get the average number, we must divide 3 into 6, which gives us 2. Now, lets take the formula above and apply it to JavaScript. Calculating the average / mean using JavaScript. Take a look at the following example:
For calculating average, take the sum of numbers in list & divide sum with number of elements in list. All Programs Simple Python Programs Decision Making Loop Functions Files Arrays or List
Here is one method:
$ awk '{s+=$1}END{print "ave:",s/NR}' RS=" " file ave: 54.646
Another option is to use jq
:
$ seq 100|jq -s add/length 50.5
-s
(--slurp
) creates an array for the input lines after parsing each line as JSON, or as a number in this case.
Or in the OP's case:
tr \ \\n<file|jq -s add/length|sed s/^/ave:\ /
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With