1

If i have

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

and i want to find average of a,b,c in only array position 0,1,2 the output will be like 1+2+3+1+2+3+1+2+3/9 how can i do that in loop?

Nisarg
  • 1,631
  • 6
  • 19
  • 31
ADAM
  • 11
  • 3
  • Possible duplicate of [Finding the average of a list](https://stackoverflow.com/questions/9039961/finding-the-average-of-a-list) – code11 Aug 15 '18 at 19:41
  • Maybe you share the considerations you already had in order to solve this problem. SO is not a free homework machine. – sim Aug 15 '18 at 20:00

3 Answers3

2

Assuming the indexes are consecutive: you can iterate over lists, take the slice of first three elements, and do sum:

In [1083]: a=[1,2,3,4,5]
      ...: b=[1,2,3,4,5]
      ...: c=[1,2,3,4,5]
      ...: 

In [1084]: sum(sum(i[:3]) for i in [a, b, c]) / 9
Out[1084]: 2.0

Or zip with itertools.islice:

In [1085]: sum(sum(i) for i in itertools.islice(zip(a, b, c), 3)) / 9
Out[1085]: 2.0

Values from variable:

In [1086]: lists = [a, b, c]

In [1087]: indexes = 3

In [1088]: sum(sum(i[:indexes]) for i in lists) / (len(lists) * indexes)
Out[1088]: 2.0

In [1089]: sum(sum(i) for i in itertools.islice(zip(*lists), indexes)) / (len(lists) * indexes)
Out[1089]: 2.0
heemayl
  • 39,294
  • 7
  • 70
  • 76
1

There are other ways, but if you aren't opposed to numpy, it is easy, and you can avoid an explicit loop:

import numpy as np

np.mean(np.stack((a,b,c))[:,:3])

Which returns 2.0

The above says: take the mean of all values up to the 3rd for all arrays together

If you want an explicit loop, you could do:

my_list = []
for l in [a,b,c]:
    my_list.extend(l[:3])

sum(my_list) / len(my_list)

Which also returns 2.0

sacuL
  • 49,704
  • 8
  • 81
  • 106
0

You could use a list comprehension along with builtin functions so you don't have to import anything.

lists = [a, b, c]
index = 3

mean = sum([(sum(item[:index])) for item in lists])/float(index*len(lists))
berkelem
  • 2,005
  • 3
  • 18
  • 36