开发者

averages of a two dimensional list

开发者 https://www.devze.com 2023-02-12 05:56 出处:网络
Basically, th开发者_C百科e function should deliver the average of the lists within the list. Example:

Basically, th开发者_C百科e function should deliver the average of the lists within the list. Example:

lst = [[46, 27, 68], [26, 65, 80], [98, 56, 35], [98, 65, 0]]
average(lst)
>>> [47.0, 57.0, 63.0, 54.33333333333333]

My code:

def average(l):
    for i in range(len(l)):
        for j in range(len(l[0])):
            l[i] / l[j]
    return l

My coding shows up an error sign saying "TypeError: unsupported operand type(s) for /: 'list' and 'list'". I don't get what I'm doing wrong.


First - indentation is important:

Then thou must space to four. Four shall be the number of the
spacing and the number of the spacing shall be four. Five shalt
thou not space, neither shalt thou space three, excepting that
thou then proceedeth to four. Tab characters are right out.

Second - use helpful variable names. One character is usually Not Helpful.

def average(lst):
    for lstNum in range(len(lst)):
        for sublistItem in range(len(lst[lstNum])):
            lst[lstNum] / lst[sublistItem] # <-- ??
    return lst

It should be clear(er) now that sublistItem, used as an index into lst, makes no sense. If we were to replace lst[sublistItem] with lst[lstNum][sublistItem] it would be better, but then you would be dividing a list by an integer, which also makes no sense.

Third - the pattern

for num in range(len(lst)):
    val = lst[num]

is un-Pythonic; if you really need to, use

for num,val in enumerate(lst):

instead, or even better,

for val in lst:

Fourth, to get the average you need to divide the sum of the list by the number of items in it; in your code you are doing neither. Try sum(lst) and len(lst) respectively.


Consider what the type of the object you reference as l[i] would be. The initial one will be l[0] -- which is [95, 92, 86]. In other words, a list.

if you know it will always just be two deep, you need something like

for each sublist in l
    for each item in sublist
        sum = sum + item
    avg = sum / len(sublist)
    append avg to returnlist

This is carefully done in pseudocode because it's more fun to figure these things out yourself.

If you don't know how deeply the lists are nested, you're going to need to think about recursion, something like

proc: 
    for each sublist in list
        if sublist has sublists
            call proc with each sublist
        else
            call avg on sublist


One thing wrong is that in the line

l[i] / l[j]

you dont assign the result of this to anything or display it in any way. Your program DOES the operation but doesn't save it anywhere. So when you return l at the end of your function you will just get the exact same thing you sent in.

On a side note Heres something you might want to look at. It doesn't do exactly what you want but you should be able to change it to what you need. From the tutorial http://docs.python.org/tutorial/stdlib.html#quality-control

def average(values):
    """Computes the arithmetic mean of a list of numbers.

    >>> print average([20, 30, 70])
    40.0
    """
    return sum(values, 0.0) / len(values)


Let's first indent your code:

def average(l):
 for i in range(len(l)):  # Line 1
    for j in range(len(l[0])):  # Line 2
        l[i] / l[j] # Line 3
 return l
  1. l is a list of lists like [[46, 27, 68], [26, 65, 80]]
  2. At Line 1, i will be your items of outer list which are lists themselves [46,27,68]
  3. At Line 2, j will be elements of your first list only.
  4. At Line 4, you index a list with another list and it throws an error!

Few notes.

You don't have to iterate using len and range. Just iterator over the elements

for element in mylist:
   pass

Use builtin such as sum to calculate the sums (Btw, you are not doing that and averages would require it). And the logic is calculate the average of the inner elements first and then move to the outer list (if you want it).


One-line-code can do the job!

list(map(lambda x:sum(x)/len(x), lst))


You are trying to divide a list by an number (l[i] is a list. e.g. [46, 27, 68]).

I would write it the same way I would do it on paper: one value at a time. I'd look at the first list, sum them up and divide by the number in the list. then rise and repeat on the next list.

def average(numbers):
    averages = []
    for group in numbers:
        group_sum = 0
        for value in group:
            group_sum += value
        averages.append(group_sum / len(group))
    return averages

If you've been taught some functions to use then use them. (e.g. sum(group) instead of doing that manually.) Your teacher is not looking for the answer as much as they are looking that you have learnt what they are teaching.

So the question is what are they teaching you? (That is a rhetorical question.)

0

精彩评论

暂无评论...
验证码 换一张
取 消