drastega - 1 month ago 8

Python Question

I have a list of even number of float numbers:

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

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

Answer

```
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]`

is the elements `2.34, 4.56, 2.34`

`data[1::2]`

is the elements `3.45, 1.23, 7.89`

`zip`

combines them into 2-tuples: `(2.34, 3.45), (4.56, 1.23), (2.34, 7.89)`