'Take the mean values of a number of integers in one list, based on the integers in another list

I have one list containing a large number of integers, and then another list also containing integers that (if added together) sums up to the total amount of integers in the first list. I wish to create a function which iterates over the second list, and for each number in the second list, takes the mean of the values in the first list and repeats for all integers in the second list...making one final third list containing the desired mean-values.

For example: A small portion of my two lists look like this: [20, 15, 20, 30, 40, 20, 10, 8], [2, 3, 1, 2]

So since 2 is the first number in my second list, I want to take the mean of the first two integers in my first list, and then the 3 next, and so on, and add these into a third list.

Here is a brief idea of what I am thinking, but its obviously not complete.

def mean_values(list_of_numbers, numbers_for_meanvalue):
        list_of_means = []
        for i in numbers_for_meanvalue:
             mean = sum(list_of_numbers[0]+...+list_of_numbers[i])/numbers_for_meanvalue[i]
             list_of_means.append[mean]
        return list_of_means


Solution 1:[1]

you can take a slice of a list: list[start : end].

def mean_values(list_of_numbers, numbers_for_meanvalue):
        list_of_means = []
        last_start = 0
        for num in numbers_for_meanvalue:
             mean = sum(list_of_numbers[last_start:last_start + num]) / len(list_of_numbers[last_start:last_start + num])
             last_start += num
             list_of_means.append[mean]
        return list_of_means

Solution 2:[2]

I don't if I understand you correctly, but:

>>> a = [20, 15, 20, 30, 40, 20, 10, 8]
>>> b = [2, 3, 1, 2]
>>> n = 0
>>> for e in b:
...     sl = a[n:n+e]
...     print(sl,(sum(sl) / e))
...     n += e
...
[20, 15] 17.5
[20, 30, 40] 30.0
[20] 20.0
[10, 8] 9.0

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2