Meysam - 1 year ago 59

Python Question

I have an array. I want to create a new array which is the average over every third element. So the new array will be a third of the size as the original.

As an example:

`[1,2,3,1,2,3,1,2,3]`

should return the array:

`[2,2,2]`

Can anyone suggest an efficient way of doing this? I want to do this without using numpy.

Answer Source

what is the problem?

```
a = [1,2,3,4,5,6,7,8,9]
def reduce_list(any_list, number_of_values_to_combine):
ret_list = []
for i in range(len(any_list)//number_of_values_to_combine):
new_value = 0
for j in range(number_of_values_to_combine):
new_value += any_list[i*number_of_values_to_combine + j]
ret_list.append(new_value/number_of_values_to_combine)
return ret_list
print reduce_list(a,3)
```

rest will be ignored, if there are f.e. 7 elements combined to 3 there will be 2 elements in the result