简体   繁体   中英

How to find the average of a nested list using a for loop?

I can't import any modules to find the average, only a 'for loop'. I essentially have to find the average of a nested list.

def get_average(map: List[List[int]]) -> float:
    """Return the average across all cells in the  map.



    >>> get_average(3X3)
    5.0
    >>> get_average(4X4)
    3.8125
    """
    total = 0
    for sublist in range(len(map)): #gives sublist 
        for i in range(sublist): #access the items in the sublist
            total = total + i 
        average = total / len(map)
    return average  

The output for get_average(4X4) is 1.0

L  =[[1, 2, 6, 5],
     [4, 5, 3, 2],
     [7, 9, 8, 1],
     [1, 2, 1, 4]]

def func(l):
    total_sum = sum([sum(i) for i in l])
    # make the sum of inner lists, store them in the list and then get the sum of final list

    count = sum([len(i) for i in l]) # get the total element in the list
    return total_sum/count # return average

print(func(L))

output

3.8125

what op code should be

def get_average_elevation(elevation_map):
    """Return the average elevation across all cells in the elevation map
    elevation_map.

    Precondition: elevation_map is a valid elevation map.

    >>> get_average_elevation(UNIQUE_3X3)
    5.0
    >>> get_average_elevation(FOUR_BY_FOUR)
    3.8125
    """
    total = 0
    count = 0
    for sublist in range(len(elevation_map)): # gives sublist index
        for i in range(len(elevation_map[sublist])): # gives index of item in sublist
            count+=1
            total = total + elevation_map[sublist][i] 

    return total/count

l = [[1, 2, 6, 5],
                [4, 5, 3, 2],
                [7, 9, 8, 1],
                [1, 2, 1, 4]]

print(get_average_elevation(l))

why coming defference, this is beacause

let say a list is l = [1,2,3,4]

so for this list for i in range(len(l)) will iterate 4 times only, but it wont give elemnt inside list ( which op thought it will give),but range return a object which iterate in inclusive range, easy term it give list from start to end-1.

what op want was element inside the list for this he need to use for element in list this will give indivitual element, in this quest regard inner list.

also to get the avg, op need to get sum of all element, which he is geeting but he need to make the avg outside the for loop.

also op need a counter to count the total no of elements to get the average.

You misunderstand the difference between an index and the list contents.

for sublist in range(len(elevation_map)): #gives sublist 

No, it does not. sublist iterates through the indices of elevation_map , the values 0-3.

    for i in range(sublist): #access the items in the sublist

Again, no. i iterates through the values 0- sublist , which is in the range 0-3.

As a result, total winds up being the sum 0 + (0 + 1) + (0 + 1 + 2) = 4 . That's how you got a mean of 1.0

Instead, write your loops to work as your comments describe:

def get_average_elevation(elevation_map):
    """Return the average elevation across all cells in the elevation map
    elevation_map.

    Precondition: elevation_map is a valid elevation map.

    >>> get_average_elevation(UNIQUE_3X3)
    5.0
    >>> get_average_elevation(FOUR_BY_FOUR)
    3.8125
    """
    total = 0
    for sublist in elevation_map: #gives sublist 
        for i in sublist: #access the items in the sublist
            total = total + i 
        average = total / len(elevation_map)
    return average  

Now, this adds up all 16 elements and divides by the quantity of rows , giving you 15.25 as the result. I think you want the quantity of elements , so you'll need to count or compute that, instead.

Can you take it from there?

Your code is likely not working because for sublist in range(len(elevation_map)): will iterate over a generator that produces [1,2,3,4]. You never access that actual numbers within the elevation_map array. The inner loop suffers from the same issue.

You can make the code simpler by using a list comprehension to flatten the array, then get the average from the flattened list.

flat_list = [item for sublist in elevation_map for item in sublist]
average = sum(flat_list) / len(flat_list)

You can just turn your list of lists in to a flat list, then use the sum function:

FOUR_BY_FOUR = [[1, 2, 6, 5],
                [4, 5, 3, 2],
                [7, 9, 8, 1],
                [1, 2, 1, 4]]

UNIQUE_3X3 = [[1, 2, 3],
              [9, 8, 7],
              [4, 5, 6]]

answer = [i for k in FOUR_BY_FOUR for i in k]
print(sum(answer)/16)

answer = [i for k in UNIQUE_3X3 for i in k]
print(sum(answer)/9)

This returns:

3.8125
5.0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM