97834657647563
97834657647563

Reputation: 251

Iterating over a list of lists in Python

I have this problem on my study guide that calls for a function that gets the average of two dimensional lists and prints them as one list. I don't really have experience messing with two dimensional lists therefore have no clue where to even begin attacking this problem.

example of what it should do:

avrg([[85, 23, 45], [66, 75, 54], [85, 54, 70], [34, 10, 0]])

[51.0, 65.0, 162.333333333334, 14.66666666666667]

my coding:

def avrg(L):
    for i in range(len(L)):
        for j in range(len(L[0])):
            L[i][j] / i

    return L

Where in my coding did I go wrong?

Upvotes: 1

Views: 1901

Answers (4)

riri
riri

Reputation: 509

import numpy as np
def avrg(ls):
    return map(np.average, ls)

Upvotes: 0

Himadri Choudhury
Himadri Choudhury

Reputation: 10353

There is no summing. You have to add the elements in each row, and then divide by the length (3 in this case).

Upvotes: 0

Seth Johnson
Seth Johnson

Reputation: 15172

For a start, the expression x / y results in a value but does not change x or y. If you're using Python, you might also want to think about using the actual list contents in the iteration instead of the more C-like "range" and accessors. Hopefully this should give you a strong push in the right direction to go:

def avrg( inlist ):
    result = []
    for a in inlist:
        # now "a" is just a list by itself
        n = len(a)
        total = sum(a)
        # you can fill in the rest here
    return result

Upvotes: 1

Colin
Colin

Reputation: 3752

The 1st, 2nd, and 4th numbers are the average of the 1st, 2nd, and 4th lists, but the 3rd is not. I'll assume that's a typo, and you meant '69.666...'.

You went wrong in the 'L[i][j] / i' bit. You can think of that statement as computing a value, and then dropping it; you don't assign it to anything. You might want to return a new list as well, perhaps, rather than putting values into the parameter. Also, you went wrong in the looping and indexing, and not actually calculating an average. Also, you went wrong in the j loop: what if some list has more values than another one? Also, you went 'wrong' by not making it pythonic and looping over the list with range and indexing, rather than looping over the items themselves ('for sublist in L: ...'). Also, you went 'wrong' by not using list comprehensions.

This is what I would have done:

def avrg(L):
   return [sum(sublist) / len(sublist) for sublist in L]

print(avrg([[85, 23, 45], [66, 75, 54], [85, 54, 70], [34, 10, 0]])

Upvotes: 1

Related Questions