0
def average_list(M):
'''(list of list of int) -> list of float

Return a list of floats where each float is the average of 
the corresponding list in the given list of lists.

>>> average_list([[4, 6], [5, 5]])
[5.0, 5.0]

'''
L = []

for item in M:
    for i in range(len(item)):
        avg = sum(item[i])/len(item[i])
        L.append(avg)
return L

error: average_list([[4, 6], [5, 5]]) Traceback (most recent call last): avg = sum(item[i])/len(item[i]) builtins.TypeError: 'int' object is not iterable

I want to know how to fix it, thanks a lot! And any other way to do in while loop?

Annie Zhang
  • 11
  • 1
  • 3

3 Answers3

1

What are you trying to do in your for loop? All you need is to iterate over M by value, not by index. This line for i in range(len(item)): is causing your error. Your inner for loop is not needed.

def average_list(M):
    L = []
    for item in M:
        avg = sum(item)/len(item)
        L.append(avg)
    return L

But you should Use list comprehension instead. In my opinion, it would be the most canonical way to solve your problem, not to mention the most "Pythonic":

>>> def average_list(M):
        return [sum(sublist)/len(sublist) for sublist in M]

>>> average_list([[4, 6], [5, 5]])
[5.0, 5.0]
>>> 
Community
  • 1
  • 1
Christian Dean
  • 22,138
  • 7
  • 54
  • 87
1

Your error is that item[i] is a single element, which you cannot sum or len. You did not need that inner loop and for loops would be preferred over while loops because you have a finite collection.

If using Python3, you can use the mean function, and map that over the list of lists

from statistics import mean

def average_list(M):
    return list(map(mean, M)) 

Borrowed from Finding the average of a list

Community
  • 1
  • 1
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
0

in python 3:

lst=[[4, 6], [5, 5]]
list(map(lambda x: sum(x)/len(x), lst))
Out[104]: [5.0, 5.0]

or in python 2:

from __future__ import division
lst=[[4, 6], [5, 5]]
map(lambda x: sum(x)/len(x), lst)
Out[104]: [5.0, 5.0]
Bastiaan
  • 4,451
  • 4
  • 22
  • 33