-1

I have a question about how to get the average of every 2 elements in a list in python. Ex:

a = [1, 3, 4, 1, 5, 2]

In this case, as it needs to compute (1 + 4 + 5)/3 and the next one (3 + 1 + 2)/3. The new list would have the following values:

amean = [3.3333,2]

So far I have managed to average, but I have no idea how to create a loop for it to return and start the average on the second element (3 + 1 + 2)/3.

Here's a piece of what I have done so far:

import numpy as np

a = [1.,3.,4.,1., 5., 2.]

def altElement(my_list):
    b = my_list[:len(my_list):2]
    print b
    return np.mean(b)

print altElement(a)

Does anyone have any idea how to create this loop? Here's a link for the code that I have done so far: code

piman314
  • 5,285
  • 23
  • 35
Michell
  • 33
  • 6

5 Answers5

1
import numpy as np
a = np.asarray([1, 3, 4, 1, 5, 2])

print( a[::2].mean() )        #All Odd Elements
print( a[1::2].mean() )       #All Even Elements

Output:

3.33333333333
2.0

Edit as per comment(every 24 elements)

import numpy as np
a = range(1, 73)

for i in map(None,*[iter(a)]*24):
    print( np.array(i).mean() )

Output:

12.5
36.5
60.5
Rakesh
  • 81,458
  • 17
  • 76
  • 113
  • Thanks Rakesh! This is a really smart approach! I may not have been so clear, so let me try to explain it to you. The list that I have is way bigger than this. In the example, I wanted to do every 2 values, but in my list, I would have to do it every 24 values. It would be something like: sum(i + i[24] +i[48] + i...)/n. Do you have any idea how to do it? – Michell Jul 04 '18 at 13:56
  • I have updated the snippet. Is that what your are looking for? – Rakesh Jul 04 '18 at 14:05
  • That's exactly what I was looking for! Thank you so much! This approach can solve not only even or odd elements but everything! Thanks again! – Michell Jul 04 '18 at 14:09
0

my_list[1::2].mean() will give you the other element.

piman314
  • 5,285
  • 23
  • 35
  • Thanks ncfirth, but I have a really big list, so I would need it to do it automatically. I was thinking about a while loop, but I am not sure how to approach it. – Michell Jul 04 '18 at 13:50
  • I don't understand what you mean. You've worked out the first one yourself this code will work out the average of every second element starting from the second element. What else are you trying to achieve? – piman314 Jul 04 '18 at 13:51
0

If you want pure Python and not Numpy:

mean = [sum(a[i::2]) / len(a[i::2]) for i in xrange(2)]

You may also want to add from __future__ import division or map(float, a) to avoid rounding.

jaboja
  • 2,178
  • 1
  • 21
  • 35
0

Another approach is assuming that you have an even number of elements, you can reshape the array so that the odd elements appear in the first column and the even elements appear in the second column of a 2D array, then take the mean of each column:

b = np.array([a]).reshape(-1,2).mean(axis=0)

Example Output

>>> a = [1.,3.,4.,1., 5., 2.]
>>> b = np.array([a]).reshape(-1,2).mean(axis=0)
>>> b
array([ 3.33333333,  2.        ])

The output is of course a NumPy array so if it is desired for you to have a list, simply invoke the tolist() method on the NumPy array:

>> b.tolist()
[3.3333333333333335, 2.0]
rayryeng
  • 102,964
  • 22
  • 184
  • 193
0

The following is an inefficient solution. But because the question is very basic, one might be curious to know the most basic solution first before the efficient solution which can be achieved using numpy or list comprehension

a = [1, 3, 4, 1, 5, 2]
list_1 = []
list_2 = []
for idx, elem in enumerate(a):
    if idx % 2 == 0:
       list_1.append(elem)
    else:
       list_2.append(elem)
print("Mean of the first every other elements ", sum(list_1)/float(len(list_1)))
print("Mean of the seond every other elements ", sum(list_2)/float(len(list_2)))
Heapify
  • 2,581
  • 17
  • 17
  • This is a very inefficient way of doing it. You could achieve what you want with a list comprehension instead: `list_1 = [elem for idx, elem in enumerate(a) if idx % 2 == 0]` for example. – rayryeng Jul 04 '18 at 13:56
  • I know, but the question is not about efficiency. – Heapify Jul 04 '18 at 13:58
  • That may be true, but you are encouraging bad practice. Doing a list comprehension is better. https://stackoverflow.com/questions/30245397/why-is-a-list-comprehension-so-much-faster-than-appending-to-a-list – rayryeng Jul 04 '18 at 13:58
  • I think the question is very basic, and not showing the user the basic way to solve the problem first before going to the next higher level may be encouraging bad practice. The user needs to know what is the inefficient way before implementing the efficient way – Heapify Jul 04 '18 at 14:01
  • You should probably make that clear in your answer then. – rayryeng Jul 04 '18 at 14:02
  • What if I have a really big list and want to take the average of every 24 values. Ex: sum(i + i[24] +i[48] + i...)/n. How can I approach it? – Michell Jul 04 '18 at 14:05
  • In that case, you will modify the if condition in the loop. Something like if idx % 23 == 0 – Heapify Jul 04 '18 at 14:07
  • @MichellGermano You probably should have made your original question more general rather than concentrating on just every other element. – rayryeng Jul 04 '18 at 14:11
  • @rayryeng sorry for not making it clear. It's my first time using stackoverflow. – Michell Jul 04 '18 at 14:15
  • @MichellGermano No worries at all. I appreciate that you wanted to have a more simple question which you could extend to a more general case later, but in this case going to the more general question is better since half of the answers now are no longer valid. Either way, welcome! – rayryeng Jul 04 '18 at 14:15