satyam sangeet
satyam sangeet

Reputation: 95

Adding element of a list

I have a list containing some values. I want to calculate the sum of every 5 elements and then divide it by 5 and then store it in an empty list. While doing so I am not sure if I can iterate over a list the way I am doing. Being a newbie to python, any help would be much appreciated.

My list looks like this:

enter image description here

My code is:

a = []
i = np.arange(0,125,5)
j = np.arange(5,130,5)

for q,r in i,j:
    cov = (np.sum(l[q:r]))/5
    cov.append(a)
print(a)

I am getting the following error:

enter image description here

Upvotes: 2

Views: 59

Answers (2)

I'mahdi
I'mahdi

Reputation: 24049

Instead of np.sum([i:i=+5])/5 you can use np.average(). instead of two value you can use range(0,length,5).

Try this:

a = []

for r in range(0,len(l),5):
    try:
        cov = (np.average(l[r:r+5]))
    except IndexError:
        cov = (np.average(l[r:]))
    a.append(cov)
print(a)

Upvotes: 2

Szabolcs
Szabolcs

Reputation: 4086

If numpy is not a hard requirement I'd definitely do it with something simple like this:

values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
values_avg = []

temp_sum = 0
for i in range(len(values)):
    temp_sum += values[i]
    if (i + 1) % 5 == 0:
        values_avg.append(temp_sum / 5)
        temp_sum = 0

print(values_avg)
# [3.0, 8.0, 8.0, 3.0]

Upvotes: 1

Related Questions