hozan hozan - 4 years ago 218
Python Question

Average of 2d list by only adding single row and finding the average of that single row

I want to find the average of a 2-dimensional list in Python.

This is an example of my list:

list = [[x, y, 1], [x, y, 1], [x, y, 2]]

I want to add the third row and find the average of that row only.

This is my code:

def averageList(list):
averagefile = []
sum = 0
for count in range(0, len(list)):
sum = sum + float(list[count][2])
except ValueError:
print ''
average = sum / len(list[count])
print averagefile

#return averageList

Answer Source
>>> L = [['x','y',1], ['x','y',1], ['x','y',2]]
>>> sum(entry[-1] for entry in L) / float(len(L))

This is same as:

>>> sum(entry[2] for entry in L) / float(len(L))

since the last position is index 2.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download