简体   繁体   中英

How to find average of some number in list [python]

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?

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

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

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM