-3

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.

Community
  • 1
  • 1
B Faley
  • 15,776
  • 37
  • 123
  • 205

3 Answers3

1

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

am2
  • 370
  • 5
  • 20
0
l = [1,2,3,2,1,4,3,2,4,5,6,4,3,1,5]
n = 3
sub = [l[(n-1) + i*n] for i in range(int(len(l)/n))]
avg_every_third_element = sum(sub)/len(sub)

Next time show your effort. Nobody can help you to improve your approach if there is none. And most questions (as yours here) can be solved with a little bit of research.

jbndlr
  • 4,526
  • 19
  • 30
0
a = [1,2,3,1,2,3,1,2,3]
array_result = []

for i in range(a):
    if i%3 == 0:
        new_number = (a[i]+a[i-1]+a[i-2])/3
        array_result.append(new_number)

That worked for me.

xgrimau
  • 606
  • 7
  • 19