Reputation: 31
I'm working on a problem but I'm curious about how to better format my output. Basically, I'm working with an array, which in Python is basically a list within a list, or should I say nested lists. The question I'm working on is related to average rating of movies reviews, but lets just say that the first column is a "reviewer" numbered 1-3 or 1-5 (depending on the size of the array) and the movie reviews are the rows, again this is size dependent on the array itself, 3x3, 6x6, etc. So below I will include my code.
array = [[4,6,2,5], [7,9,4,8], [6,9,3,7]]
def review(array):
'function that outputs average review of movie scores'
ncols = len(array[0]) #finds number of columns in array
total = 0
for row in array:
for el in row:
total+= el
avg = total/ncols
print(end = ' ')
print(' Reviewer average:', avg)
Now, this does work fine as far as calculations go, but what I need to do is have the 'Reviewer Average' number 1, 2, 3, or 1,2,3,4,5 based off the amount of columns in the array, or in other words it should output the column number based off the array size. So for example, a 3x3 array output like the original array in my code above should look like this:
Reviewer 1 average: 4.25
Reviewer 2 average: 11.25
Reviewer 3 average: 17.5
However, as I've stated my issue is, I can't seem to figure out how to number it to work with ANY table/array size, I want it to work regardless if it was 6x6 or 3x3, etc.
My current output looks like:
Reviewer average: 4.25
Reviewer average: 11.25
Reviewer average: 17.5
Upvotes: 2
Views: 419
Reputation: 6554
You are not taking the average correctly, so I took the liberty of also solving that issue. Now, as per your question: use enumerate
, like so:
array = [[4,6,2,5], [7,9,4,8], [6,9,3,7]]
def review(array):
'function that outputs average review of movie scores'
for i, row in enumerate(array, 1):
avg = sum(row)/len(row)
print(' Reviewer {0} average: {1}'.format(i, avg))
Output:
Reviewer 1 average: 4.25
Reviewer 2 average: 7.0
Reviewer 3 average: 6.25
Edit: updated code to incorporate erip's comment below.
Upvotes: 2
Reputation: 16935
You can use some more Pythonic constructs:
array = [[4,6,2,5], [7,9,4,8], [6,9,3,7]]
# Reviewer 1's average: (4+6+2+5)/4 = 4.25
# Reviewer 2's average: (7+9+4+8)/4 = 7
# Reviewer 3's average: (6+9+3+7)/4 = 6.25
def review(array):
'function that outputs average review of movie scores'
for i, row in enumerate(array,1):
average = sum(row) / float(len(row))
print('Reviewer {} average: {}'.format(i, average))
review(array)
which outputs the correct results:
20:01 $ python test.py
Reviewer 1 average: 4.25
Reviewer 2 average: 7.0
Reviewer 3 average: 6.25
Upvotes: 0