0

I have a list of lists

my_list = [[8,2,3], [8,3,6], [2,3,9], [7,3,6], [2,6,4], [8,5,8]]

and would like to take the average of the last n entries of the list for each of its entries. To clarify, here is an example:

The average of the entries of the last 3 lists of my_list is:

[(7+2+8)/3, (3+6+5)/3, (6+4+8)/3] = [5.67, 4.67, 6]

I did it with a bunch of loops of loops but I feel like there is a way to do it in probably a line or two of code. Any help is appreciated. Thanks

gapansi99
  • 187
  • 1
  • 1
  • 7

2 Answers2

1

use np.mean after you slice your list

import numpy as np

my_list = [[8,2,3], [8,3,6], [2,3,9], [7,3,6], [2,6,4], [8,5,8]]
n = 3

np.mean(my_list[-n:], axis=0) # -> array([5.66666667, 4.66666667, 6.        ])
It_is_Chris
  • 13,504
  • 2
  • 23
  • 41
1

Use a list comprehension and zip, with some help from statistics.mean to easily compute the mean:

my_list = [[8,2,3], [8,3,6], [2,3,9], [7,3,6], [2,6,4], [8,5,8]]
n = 3

from statistics import mean
[mean(x) for x in zip(*my_list[-n:])]

# OR using map
list(map(mean, zip(*my_list[-n:])))

output:

[5.666666666666667, 4.666666666666667, 6]
mozway
  • 194,879
  • 13
  • 39
  • 75