B.Joelene
B.Joelene

Reputation: 133

Recursively checking lists of list in python

I'm trying to calculate every 2 grades' (list's each element) averages in a recursive way.

list = [['2.5', '45'], ['59', '99']]

EDITED:

I changed my algorithm and my code is:

def a(lst):
    if lst == []:
        return 0
    else:
        return lst[0] / 2 + a(lst[1:2])


lst = [9.600000000000001, 37.2, 35.6, 34.4]
a(lst)

It calculates averages perfectly for first 2 elements of the list. I'm wondering how to generate it for all elements.

Upvotes: 0

Views: 455

Answers (2)

repzero
repzero

Reputation: 8402

example

lst=[['2.5', '45'], ['59', '99']]
averages=[(float(x)+float(y))/2 for x,y in lst]
print(averages)

Upvotes: 0

Iron Fist
Iron Fist

Reputation: 10951

This can be done with list comprehension:

   >>> lst=[['2.5', '45'], ['59', '99']]
   >> avg = [sum(map(float, x))/len(x) for x in lst]
   [23.75, 79.0]

So, what's happening in the above expression, is for every sub-list x of lst we are summing the float value of every element of this sub-list x and then diving by its length len, to get the average

Note:

Avoid naming your variables with Python Built-in names, to not shadow them during your script

Upvotes: 1

Related Questions