The session "Itertools Recipes" in module documentation itertools
contains an example of a function called grouper
which makes the grouping of N into N elements of an iterable (efficiently). Just you calculate the average of each returned group of that function.
Follow an example using the documentation example:
from itertools import zip_longest
def grouper(iterable, n, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return zip_longest(*args, fillvalue=fillvalue)
lista = [1, 2, 4, 3, 7, 4, 6, 5, 8, 1, 9, 4, 3]
for grupo in grouper(lista, n=5):
# Remove os `None` do último grupo
grupo = [num for num in grupo if num is not None]
media = sum(grupo) / len(grupo)
print(f"Grupo: {grupo!r}")
print(f"- Média: {media}")
Exit:
Grupo: [1, 2, 4, 3, 7]
- Média: 3.4
Grupo: [4, 6, 5, 8, 1]
- Média: 4.8
Grupo: [9, 4, 3]
- Média: 5.333333333333333
Edit
I’m using list comprehension along with is not None
to remove the values None
from the last group, because if I just test if the number is falsifiable the code would remove the zeros from the list.
lista = [0, 1, 2, 3, None]
ok = [n for n in lista if n is not None] # [0, 1, 2, 3]
wrong = [n for n in lista if n] # [1, 2, 3]
wrong_too = list(filter(None, lista)) # [1, 2, 3]
The average of the last group should be
5.3333...
because the last grouping has only 3 elements and not 5– fernandosavio
But you can solve using Walrus Operator:
[sum(l:=lista[i:i+r])/len(l) for i in range(0,len(lista),r)]
. I’ll leave thedocs
for the curious– fernandosavio
@fernandosavio, Thank you, updated!
– TigerTV.ru