Average of two consecutive items in a list in Python

I have a list of even numbers of floating point numbers:

[2.34, 3.45, 4.56, 1.23, 2.34, 7.89, ...].

My task is to calculate the average value of 1 and 2 elements, 3 and 4, 5 and 6, etc. What is the short way to do this in Python?

+4
source share
4 answers
data = [2.34, 3.45, 4.56, 1.23, 2.34, 7.89]
print [(a + b) / 2 for a, b in zip(data[::2], data[1::2])]

Explanation:

data[::2] are elements 2.34, 4.56, 2.34

data[1::2] are elements 3.45, 1.23, 7.89

zip combines them in 2 tuples: (2.34, 3.45), (4.56, 1.23), (2.34, 7.89)

+16
source

If the list is not too long, Paul Draper's answer is simple. If it is really long, you probably want to consider one of the other two options.


First, by using iterators, you can avoid copying around giant temporary lists:

avgs = [(a + b) / 2 for a, b in zip(*[iter(data)]*2)]

, , (, - a, b ), .

  • iter(data) .
  • [iter(data)]*2 , , , .
  • zip , . ( Python 2.x, 3.x, zip , itertools.izip, zip.)

, -, , , , .

, itertools grouper, ( more-itertools), grouper(data, 2) zip(*[iter(data)]*2), , , , . , . a > .


NumPy :

data_array = np.array(data)

:

avg_array = (data_array[::2] + data_array[1::2]) / 2

( ), 10 1/4 .


...

:

[sum(group) / size for group in zip(*[iter(data)]*size)]

NumPy . - data[::size], data[1::size],..., data[size-1::size], :

sum(data[x::size] for x in range(size)) / size

NumPy, size , , , Paul Draper:

[sum(group) / size for group in zip(*(data[x::size] for x in range(size)))]
+5
s= [2.34, 3.45, 4.56, 1.23, 2.34, 7.89, ...]

res= [(s[i]+s[i+1])/2 for i in range(0, len(s)-1, 2)]
+3
source

Just use the index for the task.

For a simple example

avg = []
list1 = [2.34, 3.45, 4.56, 1.23, 2.34, 7.89]

for i in range(len(list1)):
    if(i+1 < len(list1):
        avg.append( (list1[i] + list1[i+1]) / 2.0 )

avg2 = []
avg2 = [j for j in avg[::2]] 

avg2 is what you want. This may be easy to understand.

0
source

All Articles