Question: Instructions Write a function get _ list _ avg ( ) that expects a parameter main _ list ( a list of lists ) and
Instructions
Write a function getlistavg that expects a parameter mainlist a list of lists and returns a new list that contains the average of each sublist in mainlist. The function should return an empty list if the mainlist is empty.
The example below guides you stepbystep through the process. If you understand what needs to happen and how to accomplish it then you can go directly to writing your function and testing it with the assert statements.
### Check that the computation is correct
assert getlistavg
assert getlistavg
assert getlistavg
### Verify that the original list is unchanged
samplelist
getlistavgsamplelist # call the function on a sample list
assert samplelist # verify that sample list was unchanged
Walkthrough Example
Given a sample list it can be formatted as follows to show its structure nested sublists:
numlist
Loop over the main list to retrieve each element of this list, which is also a list:
for sublist in numlist:
printsublist
and produce
Compute an average of each sublist, which is the sum of that list divided by the number of elements in that list.
To assemble a new list that would hold the average values of each sublist, we need to create an empty list outside of the loop and then append the computed average values at the end of each iteration.
listavg
for sublist in numlist:
listavg.appendavg
printlistavg
Now that you have each step, turn them into a proper function that returns the correct result.
Hints
Refer to the following zyBook resources to review how to work with nested lists:
PA : List nesting.
PA : Iterating over multidimensional lists.
zyDE : Using builtin functions with lists.
zyDE : Twodimensional list example: Driving distance between cities.
Figure : Iterating through multidimensional lists using enumerate
Remember that you wrote calcaverage in the previous lab use it as a helper function here.
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
